0

i have a strange behavior in my code with custom directive. The link function is called multiple times but as example if want to initialize a third-part library (example maps) this behavior breaks the lib.

link: function(scope) {
    alert("invoked");
}

http://jsfiddle.net/dYs8L/1/

jsfiddle updated with the correct code

http://jsfiddle.net/dYs8L/2/

RevH
  • 58
  • 2
  • 8

1 Answers1

1

It's working as designed...ng-repeat essentially creates a new copy the markup with an isolated scope for every item in the collection. If you need to initialize something once, you'll need to do it elsewhere. You can consider putting this resource into a service; that will allow all the elements output by ng-repeat to use the same instance.

maf748
  • 768
  • 1
  • 4
  • 15
  • ok thank you for the explanation, i tried with jsfiddle to replicate my code and after your answer i understand that i need to replace track by $index with track by item.id (items ara returned by webservice) and now the link function is called once is this the right way? – RevH Mar 01 '14 at 15:03
  • I'm on my phone so I can't see your fiddle right now, but if you have a list of objects coming from a service and you want to use the id for each item in the collection, this is certainly a valid place to do it. – maf748 Mar 01 '14 at 15:17
  • Couldn't the Directive compile function be used in this case? – Vincenzo Maggio Mar 01 '14 at 15:19
  • http://www.bennadel.com/blog/2556-Using-Track-By-With-ngRepeat-In-AngularJS-1-2.htm i want swap item, insert and remove from the array without invoking the link function if it was invoked before, and the track by (costant property) is the better option. – RevH Mar 01 '14 at 15:23
  • @Vincenzo No...compile will also be called for each iteration. In addition, you won't have access to scope values in the compile phase. – maf748 Mar 01 '14 at 15:24
  • i updated my question with the corrected jsfiddle using track by item.id thanks all! – RevH Mar 01 '14 at 15:27