添加新数组项时,带有外部模板的重复angularjs指令无法正确渲染

Repeated angularjs directive with external template does not render properly when new array items are added.

本文关键字:angularjs 指令 数组 新数组 外部 添加      更新时间:2023-09-26

下面的fiddle呈现了3列递增数字,表示具有不同模板的指令:一列是内联的,一列是预加载的,另一列来自外部模板。当您选择"添加"按钮时,列会增加。当add按钮将一个新项目推到现有数组中,然后抛出以下错误时,表示具有外部模板的指令的列似乎创建了一个新数组:

TypeError:无法调用null 的方法"insertBefore"

有什么想法吗?

http://jsfiddle.net/jwanga/EaRHD/

angular.module('app',[]).controller('controller', function($scope){
    $scope.items = [1,2,3,4,5,6,7,8,9];
    $scope.add = function(){
        $scope.items.push($scope.items[$scope.items.length - 1]+1);
    }
}).directive('item1', function(){
    return{
        restrict:'E',
        replace:true,
        scope: {
            data: '=data'
        },
        template:'<li>{{data}}</li>'
    }
}).directive('item2', function(){
    return{
        restrict:'E',
        replace:true,
        scope: {
            data: '=data'
        },
        templateUrl:'item.html'
    }
}).directive('item3', function(){
    return{
        restrict:'E',
        replace:true,
        scope: {
            data: '=data'
        },
        templateUrl:'https://s3.amazonaws.com/thedigitalself-public/jsfiddle-EaRHD-template.html'
    }
});

我已经通过将指令包装在父元素中并将ng repeat移动到父元素来解决这个问题。任何关于为什么这会产生影响的见解都将受到赞赏。

http://jsfiddle.net/jwanga/EaRHD/13/

<li ng-repeat="item in items"><item-3  data="item"></item-3></li>

当我试图用富文本编辑器的html内容更新div时,我收到了同样的消息。但与您的情况不同,我的ng repeat已经是父元素了!

这个问题是因为我需要处理的元素(在ng repeat内部)还没有出现。只需添加一个简单的超时功能就可以解决这个问题,比如

setTimeout(function() {
    $(mySelector).html(htmlContent);
},1);

希望它能帮助其他人,干杯