【问题标题】:How can you add a unique id to each instance of a directive?如何为指令的每个实例添加唯一的 id?
【发布时间】:2014-04-10 09:24:01
【问题描述】:

我想为这个指令中的每个 div 添加一个唯一的 ID,以便我可以指定 google maps 应该传递的元素:

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)    
        },
    };
}).

【问题讨论】:

标签: angularjs


【解决方案1】:

您可以使用指令范围的唯一 id。

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

scope.$id 返回一个唯一的数字,每个范围实例单调递增。

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

Angular scope documentation

【讨论】:

  • 即使附加到这些 ID 的元素被动态销毁或重新创建,是否保证这些 ID 将保持唯一?我的意思是,如果在给定时间 $id = 26 并且带有此 ID 的元素被销毁,那么即使重新创建相同的元素,$id = 26 还会再次生成吗?
  • 根据$rootScope documentation,$id是单调递增的。所以是的,只要您不破坏 $rootScope,$id 将在一段时间内是唯一的。
【解决方案2】:

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

例如会生成:1397123701418

【讨论】:

    【解决方案3】:

    添加一个负责返回唯一 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)    
            },
        };
    }).
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-07
      • 2016-04-29
      • 2019-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-07
      相关资源
      最近更新 更多