0

我想在ngrepeat中动态地添加指令。请参考以下链接小提琴:Fiddle Link在ngrepeat中动态添加指令时出现奇怪的行为

代码:

// Code goes here 
var app = angular.module('myApp',[]); 

// myDir Directive 
app.directive('myDir', function() { 
    var controller = ['$scope','$compile', function ($scope,$compile) { 

    $scope.names=[{id:'1',directive:'subDir1'},{id:'2',directive:'subDir2'}]; 

    $scope.loadDynamicDir = function(id, directive) { 
     var newScope = $scope.$new(true); 
     var html = $compile('<div class="' + directive + '"></div>')(newScope); 
     angular.element(document.getElementById('div' + id)).append(html); 
    } 
    }] 

    return { 
    controller:controller, 
    templateUrl:'myDirTemplate.html' 
    } 

}) 

// subDir1 Directive 
app.directive('subDir1', function() { 
    return { 
    restrict:'C', 
    template: 'subDir1' 
    } 
}); 

// subDir2 Directive 
app.directive('subDir2', function() { 
    return { 
    restrict:'C', 
    template: 'subDir2' 
    } 
}); 

抱歉,系统的每个指令增加3倍。任何人都可以解释确切的行为?

+0

,WH我在子指令中使用templateUrl,它引发错误。同样的小提琴链接是[这里](https://plnkr.co/edit/bu6GfqKVafLcxPc7UFO7?p=preview) – Teja

回答

0

这很简单。添加到模板每个函数为$digest周期运行两次将运行至少两次 - 模型变化后第一,二来检查是否第一循环改变任何模型

所以你的功能loadDynamicDir将运行每次有$digest因为你追加HTML每次它创造了更多的节点

我添加按钮,将显示plunker添加更多的行为

https://plnkr.co/edit/4hpVDOPJm2BMzSwRcm5N?p=preview

<body ng-app="myApp"> 
    <my-dir></my-dir> 
    <button ng-click="$digest()">do digest</button> 
</body> 
+0

谢谢,你能解释一下这种行为吗 - 当我在子指令中使用templateUrl时,它会抛出错误。 [Fiddle Link](https://plnkr.co/edit/bu6GfqKVafLcxPc7UFO7?p=preview) – Teja

+0

这是相同的,无限的摘要。每次编译指令时,都会触发$ digest,并且每次运行$ digest时,都会从模板中触发该函数并进行另一次编译,如此等等(如果摘要没有限制) – maurycy

相关问题