2014-04-10 11 views
10

मैं इस निर्देश में प्रत्येक div करने के लिए एक अद्वितीय 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

[तत्वों के लिए निर्देशक टेम्पलेट अद्वितीय आईडी] की संभावित डुप्लिकेट (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 = 26' और इस आईडी को ले जाने वाला तत्व नष्ट हो जाता है, तो क्या उसी तत्व को फिर से बनाया जाने पर भी' id id = 26' फिर से उत्पन्न किया जाएगा? –

+0

[$ रूटस्कोप दस्तावेज़ीकरण] के अनुसार (https://docs.angularjs.org/api/ng/type/$rootScope.Scope), $ आईडी monotonically बढ़ रहा है। तो हाँ, $ id उस समय अद्वितीय होगा जब तक आप $ rootScope को नष्ट नहीं करते। – Techniv

5

एक सेवा है जो विशिष्ट आईडी के वापस जाने के लिए जिम्मेदार है जोड़ें।

उदाहरण:

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

    var nextId = 1; 

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

और फिर बस अपने निर्देश में इस सेवा इंजेक्षन और इसे कहते में एक विशिष्ट आईडी प्राप्त करने के लिए:

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

साफ समाधान! तुमने अभी मेरा दिन बचा लिया! धन्यवाद –

संबंधित मुद्दे