AngularJS笔记整理 指令交互 为不同的元素绑定方法

HTML

 1 <!doctype html>
 2 <html ng-app="MyModule">
 3 
 4 <head>
 5     <meta charset="utf-8">
 6     <link rel="stylesheet" href="css/bootstrap-3.0.0/css/bootstrap.css">
 7     <script src="framework/angular-1.3.0.14/angular.js"></script>
 8     <script src="Directive&Directive.js"></script>
 9 </head>
10 
11 <body>
12     <div class="row">
13         <div class="col-md-3">
14             <superman strength>动感超人---力量</superman>
15         </div>
16     </div>
17     <div class="row">
18         <div class="col-md-3">
19             <superman strength speed>动感超人2---力量+敏捷</superman>
20         </div>
21     </div>
22     <div class="row">
23         <div class="col-md-3">
24             <superman strength speed light>动感超人3---力量+敏捷+发光</superman>
25         </div>
26     </div>
27 </body>
28 
29 </html>

 

JS

 1 var myModule = angular.module("MyModule", []);
 2 myModule.directive("superman", function() {
 3     return {
 4         scope: {},
 5         restrict: 'AE',
 6         controller: function($scope) {
 7             $scope.abilities = [];
 8             this.addStrength = function() {
 9                 $scope.abilities.push("strength");
10             };
11             this.addSpeed = function() {
12                 $scope.abilities.push("speed");
13             };
14             this.addLight = function() {
15                 $scope.abilities.push("light");
16             };
17         },
18         link: function(scope, element, attrs) {
19             element.addClass('btn btn-primary');
20             element.bind("mouseenter", function() {
21                 console.log(scope.abilities);
22             });
23         }
24     }
25 });
26 myModule.directive("strength", function() {
27     return {
28         require: '^superman',
29         link: function(scope, element, attrs, supermanCtrl) {
30             supermanCtrl.addStrength();
31         }
32     }
33 });
34 myModule.directive("speed", function() {
35     return {
36         require: '^superman',
37         link: function(scope, element, attrs, supermanCtrl) {
38             supermanCtrl.addSpeed();
39         }
40     }
41 });
42 myModule.directive("light", function() {
43     return {
44         require: '^superman',
45         link: function(scope, element, attrs, supermanCtrl) {
46             supermanCtrl.addLight();
47         }
48     }
49 });

 

posted @ 2016-10-18 11:10  星河mio  阅读(205)  评论(2编辑  收藏  举报