【问题标题】:Force the ngRepeat directive instantiates a template each time强制 ngRepeat 指令每次都实例化一个模板
【发布时间】:2021-06-20 06:52:11
【问题描述】:

我有以下指令:

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

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

<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-repeat 再次构建指令吗?

【问题讨论】:

    标签: javascript angularjs angularjs-ng-repeat


    【解决方案1】:

    使用服务来管理您的 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>

    【讨论】:

    • 感谢您的回复。该服务不是解决方案。我需要在模板初始化期间有一个唯一的 id。重要的部分是 id 属性:
      blabla
      。在我的情况下,我不能在链接期间设置此属性。
    猜你喜欢
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    相关资源
    最近更新 更多