本文將介紹AngularJS中指令間的交互方法。
假設(shè)我們有這樣一個(gè)場(chǎng)景,
在一個(gè)html元素中有多條指令,且指令間有一些邏輯上的交互。
那么,我們?nèi)绾蝸?lái)創(chuàng)建這些指令,而且讓這些指令能夠交互起來(lái)呢?
看下面的html代碼,
<superman strength>動(dòng)感超人---力量</superman>
<superman strength speed>動(dòng)感超人2---力量+敏捷</superman>
<superman strength speed light>動(dòng)感超人3---力量+敏捷+發(fā)光</superman>
從代碼中可以看出,上面html代碼中包含了4個(gè)自定義的指令superman
,strength
,speed
和light
。
其中superman
指令的代碼如下,
var myModule = angular.module("MyModule", []);
myModule.directive("superman", function() {
return {
scope: {},
restrict: 'AE',
controller: function($scope) {
$scope.abilities = [];
this.addStrength = function() {
$scope.abilities.push("strength");
};
this.addSpeed = function() {
$scope.abilities.push("speed");
};
this.addLight = function() {
$scope.abilities.push("light");
};
},
link: function(scope, element, attrs) {
element.bind("mouseenter", function() {
console.log(scope.abilities);
});
}
}
});
superman
指令中的scope
屬性表示該指令的獨(dú)立作用域,指令的獨(dú)立作用域其實(shí)是跟指令的實(shí)例綁定的,即不同的指令實(shí)例,其獨(dú)立作用域是不同的。這是復(fù)用指令的必要條件。
superman
指令中的restrict
屬性表示該指令的使用形式。有4個(gè)選項(xiàng):EAMC??梢詤⒖贾暗?a rel="external nofollow" target="_blank" target="_blank">一篇文章,這里不多作解釋。
superman
指令中的controller
屬性是指令內(nèi)部的控制器。其目的一般是為該指令暴露一些接口供外部使用。控制器函數(shù)的參數(shù)$scope
就是指向該指令的獨(dú)立作用域。
其他三個(gè)指令的代碼如下,
myModule.directive("strength", function() {
return {
require: '^superman',
link: function(scope, element, attrs, supermanCtrl) {
supermanCtrl.addStrength();
}
}
});
myModule.directive("speed", function() {
return {
require: '^superman',
link: function(scope, element, attrs, supermanCtrl) {
supermanCtrl.addSpeed();
}
}
});
myModule.directive("light", function() {
return {
require: '^superman',
link: function(scope, element, attrs, supermanCtrl) {
supermanCtrl.addLight();
}
}
});
這里需要注意的地方就是,strength
,speed
及light
指令的定義中使用了require
屬性,這個(gè)require
的解釋如下,
請(qǐng)求另外的controller,傳入當(dāng)前directive的linking function中。require需要傳入一個(gè)directive controller的名稱。如果找不到這個(gè)名稱對(duì)應(yīng)的controller,那么將會(huì)拋出一個(gè)error。名稱可以加入以下前綴:
?
不要拋出異常。這將使得這個(gè)依賴變?yōu)橐粋€(gè)可選項(xiàng)。
^
允許查找父元素的controller。
在這里,這三個(gè)指令都依賴之前的superman
指令。且在指令的link
方法中使用了第四個(gè)參數(shù)supermanCtrl
,這個(gè)參數(shù)其實(shí)就是指令superman
的controller
的注入。所以在這三個(gè)指令的link
方法中可以使用superman
指令控制器中定義的幾個(gè)方法。
最開(kāi)始的那一段html代碼的運(yùn)行效果就是,
$scope.abilities
的值abilities
屬性其實(shí)是屬于獨(dú)立作用域的,所以html中每一行的superman
都會(huì)有一個(gè)獨(dú)立的abilities
屬性總結(jié):指令間的交互依賴指令的controller
創(chuàng)建一些供外部調(diào)用的接口,而調(diào)用這些接口的指令需要require
接口的指令名稱。
更多建議: