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)
},
};
}).
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
A simple solution to not introduce a bunch of extra code is to just use Date.now()
Would generate for example: 1397123701418
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)
},
};
}).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With