<!DOCTYPE HTML>
<html ng-app="MyModule">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>directive之间交互--动感超人案例</title>
<link rel="stylesheet" href="CSS/bootstrap.css">
<script src="angular.min.js"></script>
</head>
<body>
<!-- 指令间的交互
-->
<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>
</body>
<script>
var myModule = angular.module("MyModule",[]);
myModule.directive("superman",function(){
return {
scope: {},//独立作用域
restrict : "AE",
controller:function($scope){ //暴露一组public的方法给外部调用
$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){ //处理指令内部的事件 操作DOM元素
element.addClass('btn btn-primary');
element.bind("mouseenter",function(){
console.log(scope.abilities);
});
}
}
});
myModule.directive("strength",function(){
return {
require : '^superman', //require 用于引入依赖
link : function (scope, element,attrs, supermanCtrl) {
supermanCtrl.addStrength(); // 注入supermanCtrl 调用superman指令中通过controller暴露出来的方法
}
}
});
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();
}
}
});
</script>
</html>