强制ngRepeat指令每次实例化一个模板



我有以下指令:

.directive("testDir",function(){
var templateCreation = 0;
return {
template : function(){
return "<div id='myTestDirId-'"+(++templateCreation)+">Test dir : "+templateCreation+"</div>";
},
scope : {},
link: function (scope){}
}
})

我的目标是在每次创建指令时都有一个唯一的id。如果指令包含在ng重复中,那就不起作用。例如:

<test-dir></test-dir>
<test-dir></test-dir>
<div ng-repeat="r in [1,2,3]">
<test-dir></test-dir>
</div>

将导致

Test dir : 1
Test dir : 2
Test dir : 3 -> id attribute = myTestDirId-3
Test dir : 3 -> id attribute = myTestDirId-3
Test dir : 3 -> id attribute = myTestDirId-3

但我想要这个:

Test dir : 1
Test dir : 2
Test dir : 3 -> id attribute = myTestDirId-3
Test dir : 4 -> id attribute = myTestDirId-4
Test dir : 5 -> id attribute = myTestDirId-5

知道如何迫使ng重复构建指令吗?

使用服务管理id的递增。

简单示例:

angular.module('myApp', [])
.directive("testDir", function(idService) {
return {
template: function() {
return "<div class='myTestDir'>Test dir : {{id}}</div>";
},
scope: {},
link: function(scope) {
scope.id = idService.getId()
}
}
}).service('idService', function() {
this.id = 0
this.getId = () =>  ++this.id;   
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp">
<test-dir></test-dir>
<test-dir></test-dir>
<div ng-repeat="item in [1,2,3]">
<test-dir></test-dir>
</div> 
</div>

最新更新