本实例主要展示controller和link参数的使用.以及多个指令同时作用的情况.
1 <!DOCTYPE html> 2 <html ng-app="myModule"> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <div> 9 <div> 10 <superman strength>动感超人---力量</superman> 11 </div> 12 <div> 13 <superman strength speed>动感超人---力量+速度</superman> 14 </div> 15 <div> 16 <superman strength speed light>动感超人---力量+速度+发光</superman> 17 </div> 18 </div> 19 20 </body> 21 <script type="text/javascript" src="../js/angular1.4.3.js"></script> 22 <script type="text/javascript"> 23 var myModule=angular.module("myModule",[]); 24 myModule.directive("superman", function () { 25 return{ 26 scope:{}, 27 restrict:"AE", 28 controller:function($scope){ 29 $scope.abilities=[]; 30 this.addStrength= function () { 31 $scope.abilities.push("strength"); 32 }; 33 this.addSpeed= function () { 34 $scope.abilities.push("speed"); 35 }; 36 this.addLight= function () { 37 $scope.abilities.push(‘light‘); 38 }; 39 }, 40 link: function (scope,element,attrs) { 41 element.bind("mouseenter", function () { 42 console.log(scope.abilities); 43 }) 44 } 45 } 46 }); 47 myModule.directive("strength", function () { 48 return{ 49 require:"^superman", 50 link: function (scope, element, attrs, supermanCtrl) { 51 supermanCtrl.addStrength(); 52 } 53 } 54 }); 55 myModule.directive("speed", function () { 56 return{ 57 require:"^superman", 58 link: function (scope, element, attrs, supermanCtrl) { 59 supermanCtrl.addSpeed(); 60 } 61 }; 62 }); 63 myModule.directive("light", function () { 64 return{ 65 require:"^superman", 66 link: function (scope,element,attrs,supermanCtrl) { 67 supermanCtrl.addLight(); 68 } 69 } 70 }) 71 </script> 72 </html>
时间: 2024-10-31 11:07:12