假設需要烹飪一道菜餚,有3種原料,可以同時使用所有的3種原料,可以使用其中2種,也可以使用其中1種。
如果以Directive的寫法,大致是:<bread material1 material2 material3></bread>,或者是<bread material1 material2></bread>...
由此,我們需要自定義一個名稱是bread的directive,以元素的方式呈現;需要自定義名稱是material1的direcitve,名稱是material2的directive,...
我們需要在bread這個directive中首先定義好所有的原料即方法,比如有material1, material2, material3,然后在material1這個directive中需要調用bread這個directive中的material1方法。
這就涉及到了direcitve之間的交互和相互調用了。
如何交互呢?
其實,在direcive中為我們提供了一個require字段,此處用來聲明需要調用的外部directive。
假設以這樣的發那個是定義一個directive.
app.directive("first", function(){
return {
restrict:"E",
scope:{},//保持獨立的scope
controller: function($scope){
$scope.abilities = [];
this.addPower = function(){
$scope.abilities.push("power");
}
this.addVelocity = function(){
$scope.abilities.push("velocity");
}
this.addFly = function(){
$scope.abilities.push("fly");
}
},
link:function(scope, element){
element.bind("mouseenter", function(){
console.log(scope.abilities);
})
}
}
})
scope字段保證了scope的獨立性,並且是以元素形式聲明。
然后,分別針對以上first這個directive的3各方法自定義3個directive.
app.directive("power", function(){
return{
require:"first",
link: function(scope, element, attrs, first){
first.addPower();
}
}
})
app.directive("velocity", function(){
return{
require:"first",
link: function(scope, element, attrs, first){
first.addVelocity();
}
}
})
app.directive("fly", function(){
return{
require:"first",
link: function(scope, element, attrs, first){
first.addFly();
}
}
})
以上,通過require獲取到其它direcitive.
在頁面中按如下調用:
<first power velocity fly>Superman</first>
