• angularJS1笔记-(13)-自定义指令(controller和controllerAs实现通信)


    index.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
    <div ng-app="myApp">
        <div  ng-controller="firstController">
            <div book-list></div>
        </div>
    </div>
    
    <script type="text/javascript" src="../../vendor/angular/angularJs.js"></script>
    <script type="text/javascript" src="app/index.js"></script>
    
    <script>
    </script>
    
    </body>
    </html>
    

      index.js:

    var myApp = angular.module('myApp', [])
        .directive('bookList', function () { //bookList对应view层的book-list
            return {
                restrict: 'ECAM',
                controller: function ($scope) {
                    $scope.books = [
                        {
                            name: 'php'
                        },
                        {
                            name: 'js'
                        },
                        {
                            name: 'java'
                        }
                    ];
                    this.addBook = function () {
                        //$scope.$apply为全局刷新 在更新完model层数据源$scope.books后也要刷新view层显示
                        $scope.$apply(function () {
                            $scope.books.push({
                                name:'iOS'
                            })
                        })
                    }
                },
                controllerAs: 'bookListController', //起一个别名
                template: '<div><ul><li ng-repeat="book in books">{{book.name}}</li></ul><book-add></book-add></div>',
                replace: true
            }
        })
        .directive('bookAdd',function () {
            return{
                restrict:'ECAM',
                require:'^bookList',//^代表向上找标签约束<book-add></book-add>
                template:'<button type="button">添加</button>',
                replace:true,
                link:function (scope, iElement, iAttrs, bookListController) {//把controllerAs: 'bookListController' 注入进来
                    iElement.on('click',bookListController.addBook);
                }
            }
        })
        .controller('firstController', ['$scope', function ($scope) {
               //代表当前是给firstController服务的
        }]);
    

      运行结果:

  • 相关阅读:
    PHP $_SERVER变量
    Buddy system伙伴分配器实现
    Linux iconv使用
    内存管理(memory allocation内存分配)
    内存碎片
    《STL源码剖析》chapter2空间配置器allocator
    Effective C++学习笔记:初始化列表中成员列出的顺序和它们在类中声明的顺序相同
    c++ explicit
    《STL源码剖析》环境配置
    C++ STL的各种实现版本
  • 原文地址:https://www.cnblogs.com/yk123/p/6887019.html
Copyright © 2020-2023  润新知