angularJS 自定义指令 属性:require
发布时间:2020-12-17 09:50:40 所属栏目:安全 来源:网络整理
导读:示例展示一个指令的template中使用到了另一个指令的例子。 示例html: div ng-app="myApp" div ng-controller="firstController" div book-list/div /div/div js: angular.module('myApp',[]) //定义第一个指令 bookList .directive('bookList',function(){ r
示例展示一个指令的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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- shell 脚本攻略
- Webservice使用和开发指南
- angularjs – 离子平台准备好的事件发生两次
- scala – 为什么延迟工厂方法在F的上下文中具有返回值
- Controller中错误 TypeError: $rootScope.$broadcast is no
- WebService另一种轻量级实现—Hessian 学习笔记
- angular – 如何取消订阅/停止Observable?
- 使用RESTful Jersey框架搭建WebService,Hibernate框架访问数
- angular导出文件保存在本地
- angularjs – 如何告诉gulp-connect打开index.html,无论URL