可以在返回任何内容之前在指令中运行 javascript,也可以在返回任何内容之前在指令的编译步骤中运行 javascript:
angular.module('foo').directive('fooDirective', [function(){
console.debug('before return');
return {
restrict: 'E',
controller: function($scope){
console.debug('controller');
},
compile: function(scope, elem){
console.debug('compile');
return {
pre: function(scope,elem, attr){
console.debug('pre');
},
post: function(scope,elem,attr){
console.debug('post');
}
}
}
}
}]);
<body ng-app="foo">
<foo-directive></foo-directive>
<foo-directive></foo-directive>
</body>
这会产生以下控制台日志顺序:
before return
compile
compile
controller
pre
post
controller
pre
post
我对此有几个问题:
1)为什么我会在返回实际指令对象之前运行代码?什么是用例?
2) 为什么我想在返回前/后链接函数之前运行代码?预链接步骤与编译步骤有何不同?什么是用例?
3)当有两个项目时,为什么编译会连续运行两次,而其他所有项目都以与元素数量无关的相同顺序迭代运行?