我的自定义指令编译函数在ngRepeat(priority = 1000)和ngInclude(priority = 400)之前执行,尽管默认优先级为0,所以它应该在执行之后执行。
代码段显示myDir指令附加的内容丢失,仅显示ngInclude模板中包含的内容:
angular.module("app", [])
.run(function($templateCache) {
$templateCache.put('test.html', '<p>Content included by ngInclude</p><span>Number {{$index}}</span>');
})
.directive("myDir", function() {
return {
compile: function(elm){
elm.append('<span>apended by directive myDir, 1+1={{1+1}}</span>');
return function link(){};
}
};
})
.controller("myApp", function($scope){
$scope.items = [1,2,3];
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myApp">
<div ng-repeat="item in items" my-dir="" ng-include="'test.html'"><p>First content</p></div>
</div>
&#13;
我在jsfiddle中有相同的代码:jsfiddle-link 它显示了预期的行为。显示来自指令的附加文本。 由于优先级最低的文本是在ngRepeat和ngInclude编译函数之后附加的。
示例之间的差异仅在角度版本中。 Snipped在v1.2.23上运行(与运行v1.3.0的项目中的行为相同),jsfiddle在v1.2.1上运行
欢迎任何建议,提前谢谢;)
PS:在jsfiddle示例中,有&#34; <span>Number {{$index}}</span>
&#34;部分缺失,为那些告诉我原因的人提供额外分数。
答案 0 :(得分:0)
似乎他们添加了ngIncludeFillContentDirective
指令(也在ngInclude
名称下注册),它取代了整个html:
var ngIncludeFillContentDirective = ['$compile',
function($compile) {
return {
restrict: 'ECA',
priority: -400,
require: 'ngInclude',
link: function(scope, $element, $attr, ctrl) {
if (/SVG/.test($element[0].toString())) {
// WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
// support innerHTML, so detect this here and try to generate the contents
// specially.
$element.empty();
$compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
function namespaceAdaptedClone(clone) {
$element.append(clone);
}, {futureParentElement: $element});
return;
}
$element.html(ctrl.template);
$compile($element.contents())(scope);
}
};
}];
它的运行优先级为-400,因此你的指令在ngRepeat和ngInclude之后但在此之前执行。
答案 1 :(得分:0)
我不确定,但我认为问题在于ngInclude是终端。
ng documentation:
终端
如果设置为true,则当前优先级将是最后一组 将执行的指令(当前优先级的任何指令 仍将按相同优先级的执行顺序执行 未定义)。注意表达式和其他指令 指令的模板也将被排除在执行之外。
这是我的解决方法(链接fn中的DOM操作而不是编译fn):
angular.module("app", [])
.run(function($templateCache) {
$templateCache.put('test.html', '<p>Content included by ngInclude</p><span>Number {{$index}}</span>');
})
.directive("myDir", function($compile) {
return {
link: function(scope, elm){
elm.append($compile('<br><span>apended by directive myDir, 1+1={{1+1}}</span>')(scope));
}
};
})
.controller("myApp", function($scope){
$scope.items = [1,2,3];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myApp">
<div ng-repeat="item in items" my-dir="" ng-include="'test.html'"><p>First content</p></div>
</div>