angularjs中的指令
一、指令与控制器之间的交互:通过指令中的link函数来实现
<body ng-app="myApp" ng-controller="myCtrl">
<my-print>鼠标进入触发打印</my-print>
<script>
angular.module('myApp',[])
.controller('myCtrl',function($scope){
$scope.print=function(){
console.log('我是打印数据....')
}
})
.directive('myPrint',function(){
return{
restrict:'E',
link:function(scope,element,attrs){
element.bind('mouseenter',function(){
scope.print();
})
}
}
})
</script>
</body>
二、指令与指令间的交互:
<body ng-app="myApp">
<div>
<superman strength>动感超人--力量</superman>
</div>
<div>
<superman strength speed>动感超人--力量+敏捷</superman>
</div>
<div>
<superman strength speed light>动感超人--力量+敏捷+发光</superman>
</div>
<script>
var app=angular.module('myApp',[])
app.directive('superman',function(){
return{
restrict:'E',
scope:{},
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);
})
}
}
})
app.directive('strength',function(){
return{
require:'^superman',
link:function(scope,element,attrs,supermanCtrl){
supermanCtrl.addStrength();
}
}
})
app.directive('speed',function(){
return{
require:'^superman',
link:function(scope,element,attrs,supermanCtrl){
supermanCtrl.addSpeed();
}
}
})
app.directive('light',function(){
return{
require:'^superman',
link:function(scope,element,attrs,supermanCtrl){
supermanCtrl.addLight();
}
}
})
</script>
</body>
三、示例说明
1.自定义指令下的link函数有四个参数:scope,element,attrs和ctrl(关联ctrl)
2.require:请求另外的controller,传入当前directive的link 函数中。require需要传入一个directive controller的名称。如果找不到这个名称对应的controller,那么将会抛出一个error。名称可以加入以下前缀:
? - 不要抛出异常。这使这个依赖变为一个可选项。
^ - 允许查找父元素的controller
3.在上面的示例中<superman></superman>指令中添加的strength speed light其实也是指令,是以属性的方式存在的。
浙公网安备 33010602011771号