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

index.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: '
  • {{book.name}}
', replace: true } }) .directive('bookAdd',function () { return{ restrict:'ECAM', require:'^bookList',//^代表向上找标签约束 template:'', replace:true, link:function (scope, iElement, iAttrs, bookListController) {//把controllerAs: 'bookListController' 注入进来 iElement.on('click',bookListController.addBook); } } }) .controller('firstController', ['$scope', function ($scope) { //代表当前是给firstController服务的 }]);

  运行结果:

angularJS1笔记-(13)-自定义指令(controller和controllerAs实现通信)_第1张图片

 

转载于:https://www.cnblogs.com/yk123/p/6887019.html

你可能感兴趣的:(angularJS1笔记-(13)-自定义指令(controller和controllerAs实现通信))