问题描述
限时送ChatGPT账号..指令代码:
.directive('replace', function($compile) {返回函数(范围,元素){element.html(element.html().replace("Hej", "嘿!"));$compile(element.contents())(scope);}});})
HTML
<div replace>Hej <div ng-repeat="e in arr">{{ e }}</div>
控制器
app.controller('GreeterController', ['$scope', function($scope) {$scope.arr = [1, 2, 3, 4];}]);
实例
正如标题所说,当我在包含它的 HTML 上使用上面的指令时,ng-repeat
不起作用.但是,一旦我删除了使用 .replace()
命令替换部分 HTML 的那一行,ng-repeat
就会出于某种原因开始工作.
有谁知道真正的问题在哪里?我已经尝试了所有方法,但我似乎仍然不明白为什么它不能正常工作.
操作也可以在编译阶段完成:
app.directive("替换", function(){返回 {编译:函数(元素){element.html(element.html().replace('Hej', '嘿!'));/*返回 {前:功能(范围,元素){element.html(element.html().replace('Hej', '嘿!'));}}*/}};});
最初的问题是因为 ng-repeat
指令的链接是在带有该指令的元素被替换操作替换之前完成的.与 ng-repeat
指令关联的观察者然后对不再附加到可见 DOM 的元素进行操作.
通过将替换操作移动到编译阶段或预链接阶段,具有 ng-repeat
指令的元素的替换在 ng-repeat
指令之前完成> 指令已链接.与 ng-repeat
指令关联的观察者然后使用替换的 DOM.
Directive code:
.directive('replace', function($compile) {
return function (scope, element) {
element.html(element.html().replace("Hej", "Hey!"));
$compile(element.contents())(scope);
}
});
})
HTML
<div ng-controller="GreeterController">
<div replace>Hej <div ng-repeat="e in arr">{{ e }}</div>
</div>
</div>
Controller
app.controller('GreeterController', ['$scope', function($scope) {
$scope.arr = [1, 2, 3, 4];
}]);
Live example
As the title says, ng-repeat
doesn't work when I'm using the directive from above on HTML which contains it.
But once I remove that line which uses .replace()
command to replace part of HTML then ng-repeat
starts working for some reason.
Does anyone know where's the actual problem?
I have tried everything and I still seem to not get it why it doesn't work as it should.
The manipulation can also be done in the compile phase:
app.directive("replace", function(){
return {
compile: function(element){
element.html(element.html().replace('Hej', 'Hey!'));
/*return {
pre: function(scope, element){
element.html(element.html().replace('Hej', 'Hey!'));
}
}*/
}
};
});
The original problem was caused because the linking of the ng-repeat
directive was done before the element with that directive is replaced with the replace operation. The watchers associated with the ng-repeat
directive then operate on elements that are no longer attached to the visible DOM.
By moving the replace operation to either the compile phase or the preLink phase, the replacing of the element that has the ng-repeat
directive is done before the ng-repeat
directive is linked. The watchers associated with ng-repeat
directive then work with the replaced DOM.
这篇关于在 $compile 下更改 HTML 时,ng-repeat 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论