【发布时间】:2014-10-04 03:54:55
【问题描述】:
AngularJS 中(前/后)链接函数的时间安排在the documentation 中有很好的定义
预链接功能
在链接子元素之前执行。做 DOM 不安全 转换,因为编译器链接函数将无法定位 链接的正确元素。
后链接功能
在子元素链接后执行。做DOM是安全的 后链接功能的转换。
和this blog post 清楚地说明了这个预期的顺序。
但在使用ng-transclude 和嵌套指令时,此顺序似乎不适用。
这是一个 dropright 元素的示例 (See the Plunkr)
<!-- index.html -->
<dropright>
<col1-item name="a">
<col2-item>1</col2-item>
<col2-item>2</col2-item>
</col1-item>
<col1-item name="b">
...
</col1-item>
</dropright>
// dropright-template.html
<div id="col1-el" ng-transclude></div>
<div id="col2-el">
<!-- Only angularJS will put elements in there -->
</div>
// col1-item-template.html
<p ng-transclude></p>
// col2-item-template.html
<div ng-transclude></div>
dropright 看起来像
当调用它们的链接和控制器函数时,指令会在控制台中写入日志。 它通常显示:
但有时(几次刷新后),顺序并不像预期的那样:
dropright post-link 函数在其子项的 post-link 函数之前执行。
这可能是因为,在我的特殊情况下,我在儿童指令中调用 dropright 控制器 (See the Plunkr)
angular.module('someApp', [])
.directive('dropright', function() {
return {
restrict: 'E',
transclude: 'true',
controller: function($scope, $element, $attrs) {
console.info('controller - dropright');
$scope.col1Tab = [];
$scope.col2Tab = [];
this.addCol1Item = function(el) {
console.log('(col1Tab pushed)');
$scope.col1Tab.push(el);
};
this.addCol2Item = function(el) {
console.log('(col2Tab pushed)');
$scope.col2Tab.push(el);
};
},
link: {
post: function(scope, element, attrs) {
console.info('post-link - dropright');
// Here, I want to move some of the elements of #col1-el
// into #col2-el
}
},
templateUrl: 'dropright-tpl.html'
};
})
.directive('col1Item', function($interpolate) {
return {
require: '^dropright',
restrict: 'E',
transclude: true,
controller: function() {
console.log('-- controller - col1Item');
},
link: {
post: function(scope, element, attrs, droprightCtrl) {
console.log('-- post-link - col1Item');
droprightCtrl.addCol1Item(element.children()[0]);
}
},
templateUrl: 'col1-tpl.html'
};
})
.directive('col2Item', function() {
var directiveDefinitionObject = {
require: '^dropright',
restrict: 'E',
transclude: true,
controller: function() {
console.log('---- controller - col2Item');
},
link: {
post: function(scope, element, attrs, droprightCtrl) {
console.log('---- post-link - col2Item');
droprightCtrl.addCol2Item(element.children()[0]);
}
},
templateUrl: 'col2-tpl.html'
};
return directiveDefinitionObject;
});
在使用转置时,在其子项的所有链接函数之后,是否有任何干净的方法来执行指令的链接函数?
【问题讨论】:
-
您使用的是哪个版本的 Angular?有许多针对 $compile 的错误修复,特别是与适用于 1.2.18 及更高版本的嵌入相关。请参阅 github.com/angular/angular.js/blob/master/… 的 1.2.18 及更高版本的发行说明
-
@Beyers:我们使用的是1.2.21版本
标签: angularjs angularjs-directive