当添加新的数组项时,使用外部模板的重复angularjs指令无法正确呈现。

11
以下代码展示了三列递增数字,分别使用不同的模板渲染指令:一个是内联模板,一个是预加载模板,还有一个来自外部模板。当您选择“添加”按钮时,这些列会递增。似乎当具有外部模板指令的列通过“添加”按钮将新项目推到现有数组中时,就会创建一个新数组,并抛出以下错误:
TypeError: Cannot call method 'insertBefore' of null
您有什么想法? 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'
    }
});
2个回答

6
我通过将指令包装在父元素中,并将ng-repeat移到父元素中来解决了这个问题。仍然欢迎任何关于为什么会有区别的见解。 http://jsfiddle.net/jwanga/EaRHD/13/
<li ng-repeat="item in items"><item-3  data="item"></item-3></li>

1
这对我也解决了问题。我也不知道为什么会这样。 - Jeppebm

1
当我试图使用富文本编辑器的HTML内容更新一个div时,我收到了同样的消息。但是与您的情况不同,我的ng-repeat已经是父元素了!
问题的根源在于我需要处理的元素(在ng-repeat内部)尚未出现。只需添加一个简单的超时函数即可解决,像这样:
setTimeout(function() {
    $(mySelector).html(htmlContent);
},1);

希望能对其他人有所帮助,谢谢!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接