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

--@angularJS--指令与指令之间的交互demo

2015-05-19 17:34 351 查看
1、index.html:

<!DOCTYPE HTML>
<html ng-app="app">
<head>
<title>custom-directive</title>
<meta charset="utf-8">
<link rel="stylesheet" href="../css/bootstrap.css">
<script src="../js/angular.js"></script>
<!--<script src="../js/jquery-1.10.2.min.js.js"></script>-->
</head>
<body>
<!-- 下面是指令与指令间的交互demo. -->
<div class="container">
<div class="row">
<div class="col-md-3"><superman strength>动感超人+力量</superman></div>
</div>
<div class="row">
<div class="col-md-3"><superman strength speed>动感超人+力量+速度</superman></div>
</div>
<div class="row">
<div class="col-md-3"><superman strength speed light>动感超人+力量+速度+发光</superman></div>
</div>
</div>

<script src="./directive-directive.js"></script>
</body>
</html>

2、directive-directive.js:

var myModule = angular.module("app",[]);

myModule.directive('superman',function(){
return {
restrict:'AE',
scope:{},
controller:function($scope){
$scope.abilities = []; //定义能力集合
this.addstrength = function(){//指令中的controller是一个公开暴露的api接口,一般是供后面定义该标签内的属性指令调用执行的
$scope.abilities.push("strength");
};
this.addspeed = function(){
$scope.abilities.push("speed");
};
this.addlight = function(){
$scope.abilities.push("light");
};
},
link:function(scope,element,attrs){//link里面可以操纵DOM元素本身以及元素属性还有全局scope作用域内的方法
element.addClass('btn btn-primary');
element.bind("mouseenter", function() {
console.log(scope.abilities);
});
}
}
}).directive('strength',function(){//一个属性代表一个值
return {//restrict:这里不写默认的是属性指令
require:'^superman',//依赖superman指令,并在link方法中注入第四个参数supermanCtrl,即superman的控制器参数,并通过该参数调用控制器里面的暴露方法
link:function(scope,element,attrs,supermanCtrl){
supermanCtrl.addstrength();
}
}
}).directive('speed',function(){
return {
require:'^superman',
link:function(scope,element,attrs,supermanCtrl){
supermanCtrl.addspeed();
}
}
}).directive('light',function(){
return {
require:'^superman',
link:function(scope,element,attrs,supermanCtrl){
supermanCtrl.addlight();
}
}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: