AngularJS中directive指令使用之事件绑定与指令交互用法示例
本文实例讲述了AngularJS中directive指令使用之事件绑定与指令交互用法。分享给大家供大家参考,具体如下:
AngularJS中模板的使用,事件绑定以及指令与指令之间的交互
<!doctypehtml> <htmlng-app="myapp"> <head> <metacharset="utf-8"/> </head> <bodyng-controller="ShieldController"> <div> <who></who> </div> <div> <buttonyou-btn></button> </div> <theshieldreigns>343</theshield> <theshieldreigns>fdhg</theshield> <theshieldrollins>hhh</theshield> <theshieldambros>kkk</theshield> </body> <scriptsrc="./js/angular.min.js"></script> <script> varapp=angular.module('myapp',[]); /*=======================1.模板的使用========================*/ app.directive('who',function(){ return{ restrict:"E",//元素element的意思 link:function(scope,element,attrs){ console.log(element); element[0].innerHTML='sdfhkj';//这个优先级别最高 }, //templateUrl:"param.html",//这个不显示优先级别最低 template:"<h1>jkdhf</h1>"//这个显示优先级别其次 }; }); /*=======================2.事件的绑定========================*/ app.directive('youBtn',function(){ return{ restrict:"A",//attribute属性的意思 link:function(scope,element,attrs){ console.log(element); element[0].innerHTML='mybtn'; //事件绑定 element.bind('mouseenter',function(){ element[0].innerHTML='yourbtn'; }); element.bind('mouseleave',function(){ element[0].innerHTML='herbtn'; }); } }; }); /*=======================3.元素属性控制器之间的交互========================*/ app.controller('ShieldController',function($scope){ $scope.shieldNames=[]; this.addReigns=function(){ $scope.shieldNames.push("reigns:jjj"); } this.addRollins=function(){ $scope.shieldNames.push("Rollins:hhh"); } this.addAmbros=function(){ $scope.shieldNames.push("Ambros:ggg"); } }) .directive('reigns',function(){ return{ require:"theshield", link:function(scope,element,attrs,ShieldController){ ShieldController.addReigns(); } }; }) .directive('rollins',function(){ return{ require:"theshield", link:function(scope,element,attrs,ShieldController){ ShieldController.addRollins(); } }; }) .directive('ambros',function(){ return{ require:"theshield", link:function(scope,element,attrs,ShieldController){ ShieldController.addAmbros(); } }; }) .directive('theshield',function(){ return{ restrict:"E", controller:"ShieldController",//指定控制器 scope:{},//清空该指令处的$scope值 link:function(scope,element,attrs){ element.bind('mouseenter',function(){//对于该指令所对应的元素绑定对应的事件 console.log(scope.shieldNames); }); } }; }); </script> </html>
希望本文所述对大家AngularJS程序设计有所帮助。