<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="UTF-8">
<title></title>
<script src="../js/angular.min.js"></script>
<script src ="js/超人.js"></script>
</head>
<body>
<div >
<superman strength>動感超人---力量</superman>
</div>
<div >
<superman strength speed>動感超人2---力量+敏捷</superman>
</div>
<div>
<superman strength speed light>動感超人3---力量+敏捷+發光</superman>
</div>
</body>
</html>
var app = angular.module('myApp',[]);
app.directive("superman",function(){
return {
scope :{},
restrict :'AE',
controller: function($scope) {//這裏的的controller是指令內部的controller,這爲了暴露方法給外部使用的
$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){//在link函數中操作dom和綁定事件監聽
// element.addListener('mouseenter',function(){
// console.log(scope.abilities);
// });
element.bind("mouseenter",function(){
console.log(scope.abilities);
});
}
}
});
app.directive("speed",function(){
return {
require : '^superman', //外部指令
link : function(scope,element,attrs,supermanCtrl){
supermanCtrl.addSpeed();
}
}
});
app.directive("strength",function(){
return {
require : '^superman',
link : function(scope,element,atrrs,supermanCtrl){
supermanCtrl.addStrength();
}
}
});
app.directive("light",function(){
return {
require : '^superman',
link: function(scope,element,attrs,supermanCtrl){
supermanCtrl.addLight();
}
}
});
如果想要暴露方法給外部使用就把方法寫在controller裏邊,l
ink:是用來操作指令內部的一些事物的,比如說操作dom,綁定事件