2014-04-10 56 views
10

我想唯一的ID添加到每个格在这个指令,让我可以指定哪些元素谷歌地图应该通过:如何为指令的每个实例添加一个唯一的ID?

directive('gMap', function(googleMaps){ 
return{ 
     restrict: 'E', 
     replace: true, 
     transclude: true, 
     template: "<div id="{{unique_ID}}"></div><div ng-transclude></div>", 
     scope: true, 
     link: function(scope, element, attrs){ 


      //create the map 
      var center = googleMaps.makePosition(attrs.centerlat, attrs.centerlong) 
      //update map on load 
      var options = googleMaps.setMapOptions(center, attrs.zoom); 
      scope.map = googleMaps.createMap(options, unique_id)  
     }, 
    }; 
}). 
+1

[为元素指令模板的唯一ID]的可能的复制(http://stackoverflow.com/questions/21021951/directive-template-unique-ids-for-elements) –

回答

23

您可以使用指令作用域的唯一标识。

<div id="gMap-{{::$id}}"></div><div ng-transclude></div> 

scope.$id返回每个范围实例单调增加的唯一编号。

'::'是使用一次性绑定,如果您使用角1.3或更高版本。

Angular scope documentation

+0

即使在动态销毁或重新创建附加到这些ID的元素时,这些ID是否仍然保持唯一?我的意思是,如果在给定时间'$ id = 26'并且带有这个ID的元素被销毁,即使重新创建了相同的元素,是否会再次生成'$ id = 26'? –

+0

根据[$ rootScope文档](https://docs.angularjs.org/api/ng/type/$rootScope.Scope),$ id单调递增。所以是的,只要你不破坏$ rootScope,$ id将会是唯一的。 – Techniv

5

添加服务,负责返回唯一的ID。

例子:

angular.module("app").service("UniqueIdService", function(){ 

    var nextId = 1; 

    this.getUniqueId = function(){ 
     return nextId++; 
    } 
}); 

,然后简单地注入该服务到您的指令,并调用它来获得一个唯一的ID:

directive('gMap', function(googleMaps, UniqueIdService){ 
return{ 
     restrict: 'E', 
     replace: true, 
     transclude: true, 
     template: "<div id="{{unique_ID}}"></div><div ng-transclude></div>", 
     scope: true, 
     link: function(scope, element, attrs){ 
      scope.unique_ID = UniqueIdService.getUniqueId(); 

      //create the map 
      var center = googleMaps.makePosition(attrs.centerlat, attrs.centerlong) 
      //update map on load 
      var options = googleMaps.setMapOptions(center, attrs.zoom); 
      scope.map = googleMaps.createMap(options, scope.unique_ID)  
     }, 
    }; 
}). 
16

一个简单的解决方案,不引入一堆额外的代码是只需使用Date.now()

会生成例如:1397123701418

+1

巧妙的解决办法!你刚刚救了我的一天!谢谢 –

相关问题