在$ compile下更改HTML时,ng-repeat不起作用 [英] ng-repeat doesn't work when HTML is altered under $compile

查看:86
本文介绍了在$ compile下更改HTML时,ng-repeat不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

指令代码:

.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>

控制器

app.controller('GreeterController', ['$scope', function($scope) {
    $scope.arr = [1, 2, 3, 4];
}]);

实时示例

正如标题所述,当我在包含该指令的HTML上使用上面的指令时,ng-repeat不起作用. 但是,一旦我删除了使用.replace()命令替换部分HTML的行,则ng-repeat由于某种原因开始工作.
有人知道真正的问题在哪里吗? 我已经尝试了所有方法,但似乎还是不明白为什么它无法正常工作.

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!'));
                }
            }*/
        }
    };
});

最初的问题是由于ng-repeat指令的链接是在用replace操作替换具有该指令的元素之前完成的.然后,与ng-repeat指令关联的监视程序将对不再附加到可见DOM的元素进行操作.

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.

通过将替换操作移至编译阶段或preLink阶段,可以在链接ng-repeat指令之前完成具有ng-repeat指令的元素的替换.然后,与ng-repeat指令关联的观察者可以使用替换后的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆