<html ng-app="MyModule">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/bootstrap-3.0.0/css/bootstrap.css">
<script src="framework/angular-1.3.0.14/angular.js"></script>
<script src="Directive&Directive.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>动感超人2---力量+敏捷</superman>
</div>
</div>
<div class="row">
<div class="col-md-3">
< superman strength speed light>动感超人3---力量+敏捷+发光</superman>
</div>
</div>
</body>
</html>
上面共有四种指令:superman、strength、speed、light,对应交互如下:
var myModule = angular.module("MyModule", []);
myModule.directive("superman", function() {
return {
scope: {},//创建独立的作用域
restrict: 'AE',
controller: function($scope) {//不同于mvc中的controller,是指令内部的controller,用来给指令暴露一组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) {
element.addClass('btn btn-primary');//给元素增加样式
element.bind("mouseenter", function() {//绑定鼠标滑动事件
console.log(scope.abilities);
});
}
}
});
myModule.directive("strength", function() {
return {
require: '^superman',//表示该指令依赖于superman指令
link: function(scope, element, attrs, supermanCtrl) {加入第四个参数superman,即可调用到控制器中暴露出来的方法
supermanCtrl.addStrength();
}
}
});
myModule.directive("speed", function() {
return {
require: '^superman',//表示该指令依赖于superman指令
link: function(scope, element, attrs, supermanCtrl) {
supermanCtrl.addSpeed();
}
}
});
myModule.directive("light", function() {
return {
require: '^superman',//表示该指令依赖于superman指令
link: function(scope, element, attrs, supermanCtrl) {
supermanCtrl.addLight();
}
}
});
什么时候把逻辑写在controller中,什么时候写在link中?
如果想让指令暴露出一些方法供外界使用,写在controller中,link是用来处理指令内部事务的