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服务的 }]);
运行结果: