示例展示一个指令的template中使用到了另一个指令的例子。
示例html:
<div ng-app="myApp"> <div ng-controller="firstController"> <div book-list></div> </div> </div>js:
angular.module('myApp',[]) //定义第一个指令 bookList .directive('bookList',function(){ return { restrict:'ECAM',controller:function($scope){ $scope.books=[ {name:'PHP'},{name:'javascript'},{name:'java'} ]; this.addBook=function(){ $scope.$apply(function(){ $scope.books.push({name:'Angularjs'}); }); } },controllerAs:'bookListController',//这个template中使用了第二个指令bookAdd template:'<div><ul><li ng-repeat="book in books">{{ book.name }}</li></ul> <book-add></book-add> </div>',replace:true } }) //定义第二个指令 bookAdd .directive('bookAdd',function(){ return{ restrict:'ECAM',require:'^bookList',template:'<button type="button">添加</button>',replace:true,link:function(scope,iElement,iAttrs,bookListController){ //这里引用了bookList指令 iElement.on('click',bookListController.addBook); } } }) .controller('firstController',['$scope',function($scope){ }])执行结果:
点击“添加”:
再点击“添加”两次:
示例中,在bookAdd指令中设置了 require : ' ^bookList ' ,指示该指令引用了bookList指令,^ 指示在父级元素查找bookList指令:
下面改进上面的例子,可以输入书名添加:
执行结果:
html和js:
<body> <div ng-app="myApp"> <div ng-controller="myCtrl"> <book-list></book-list> </div> </div> <script> angular.module('myApp',[]) .directive('bookList',function(){ return { restrict:'E',template:'<div><ul><li ng-repeat="book in books">{{ book.name }}</li></ul><book-add></book-add></div>',controller:function($scope){ $scope.books=[ {name:'book01'},{name:'book02'},{name:'book03'} ]; this.addBook=function(name){ if(typeof(name)=='undefined' || name.length<1){alert('书名不可为空!');return;} $scope.$apply(function(){ var exist=false; angular.forEach($scope.books,function(ele,i){ if(ele.name == name){ exist=true; return; } }); if(exist){alert('该书已经存在!')}else{ $scope.books.push({name:name}); } }); } },controllerAs:'bookListController' } }) .directive('bookAdd',template:'<div><input type="text" placeholder="书名" ng-model="newBookName"><button type="button">添加</button></div>',bookListController){ iElement.find('button').on('click',function(){ bookListController.addBook(scope.newBookName); }) } } }) .controller('myCtrl',function($scope){}); </script> </body>原文链接:https://www.f2er.com/angularjs/148672.html