您的位置:首页 > Web前端 > AngularJS

AngularJS中Directive间交互实现合成

2015-12-28 23:11 681 查看
假设需要烹饪一道菜肴,有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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: