1、指令的执行分两个阶段,compile和link函数
自定义link
var app = angular.module("app",[]);
app.directive("hello",function(){
return {
restrict:"E",
template:"<div>hello everyone!</div>",
replace:true,
link:function(scope,element,attr,controller){
element.on("mouseenter",function(){
console.log("i am link....");
})
}
}
})
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>compile and link</title>
<script src="../angular-1.5.8/angular.js"></script>
<script src="comAndLink.js"></script>
</head>
<body>
<hello></hello>
</body>
</html>
自定义compile
var app = angular.module("app",[]);
app.directive("myhello",function(){
return{
restrict:"A",
compile:function(element,attr,transclude){
console.log("enter compile...");
var tpl = element.children().clone();
for(var i=0;i<attr.myhello;i++){
element.append(tpl.clone());
}
return function(scope,element,attr,controller){//必须,未来作为link
console.log("指令链接。。。");
}
}
}
})
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>compile</title>
<script type="text/javascript" src="../angular-1.5.8/angular.js"></script>
<script type="text/javascript" src="comAndLink.js"></script>
</head>
<body>
<div myhello="5">
<p>你好</p>
</div>
</body>
</html>
结果:
你好
你好
你好
你好
你好
你好
同时有link和compile
app.directive("myhello",function(){
return{
restrict:"A",
compile:function(element,attr,transclude){
console.log("enter compile...");
var tpl = element.children().clone();
for(var i=0;i<attr.myhello;i++){
element.append(tpl.clone());
}
return function(scope,element,attr,controller){
console.log("指令链接。。。");
}
},
link:function(){
console.log("link.....")
}
}
})
这时link是没有执行的,因为compile返回的函数作为link,自己定义的link不起作用,所以一般不同时出现
2、compile和link的区别
1)compile函数的作用是对指令的模板进行转换
2)link的作用是在模型和视图之间建立关联,包括在元素上注册事件监听器
3)scope在链接阶段才会被绑定到元素上,因此compilce阶段操作scope会报错
4)对于同一个指令的多个实例,compilce只会执行一次,而link对于指令的每个实例都会执行一次
5)一般情况下我们只要编写link函数
6)注意,如果你编写了自定义的complice函数,自定义的linK函数无效,因为compile函数应该返回一个link函数后续处理