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

问题描述

我有以下指令:

# Vault Helm Chart Value Overrides
global:
  enabled: true
  tlsdisable: true

injector:
  enabled: true
  # Use the Vault K8s Image https://github.com/hashicorp/vault-k8s/
  image:
    repository: "hashicorp/vault-k8s"
    tag: "0.9.0"

  resources:
    requests:
      memory: 256Mi
      cpu: 250m
    limits:
      memory: 256Mi
      cpu: 250m
  affinity: ""
server:
  auditStorage:
    enabled: true
  standalone:
    enabled: false
  image:
    repository: "hashicorp/vault"
    tag: "1.6.3"
  resources:
    requests:
      memory: 4Gi
      cpu: 1000m
    limits:
      memory: 8Gi
      cpu: 1000m 
  ha:
    enabled: true
    replicas: 3    
    raft:
      enabled: true
      setNodeId: true
      config: |
        ui = true

        listener "tcp" {
          tls_disable = true
          address = "[::]:8200"
          cluster_address = "[::]:8201"
        }

        storage "raft" {
          path = "/vault/data"
        }

        service_registration "kubernetes" {}
    config: |
      ui = true

      listener "tcp" {
        tls_disable = true
        address = "[::]:8200"
        cluster_address = "[::]:8201"
      }

      service_registration "kubernetes" {}


# Vault UI
ui:
  enabled: true
  serviceType: "ClusterIP"
  externalPort: 8200

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

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

会导致

<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

知道如何强制 ng-repeat 再次构建指令吗?

解决方法

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