Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you add a unique id to each instance of a directive?

Tags:

angularjs

I want to add a unique ID to each div in this directive, so that I can specify what element that google maps should pass:

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)    
        },
    };
}).
like image 663
Himmators Avatar asked Apr 10 '14 09:04

Himmators


3 Answers

You can use the unique id of the directive's scope.

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

scope.$id return an unique number that monotonically increase for each scope instance.

The '::' is to use the one-time binding if you use angular 1.3 or later.

See Angular scope documentation

like image 187
Techniv Avatar answered Oct 21 '22 01:10

Techniv


A simple solution to not introduce a bunch of extra code is to just use Date.now()

Would generate for example: 1397123701418

like image 34
tasseKATT Avatar answered Oct 21 '22 00:10

tasseKATT


Add a service that is responsible to return unique id's.

Example:

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

    var nextId = 1;

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

And then simply inject this service into your directive and call it to get a unique 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)    
        },
    };
}).
like image 39
thomaux Avatar answered Oct 21 '22 00:10

thomaux