Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic id ng-repeat

I am trying to set a dynamic id to my div within my ng-repeat. Let me show an example.

<div id="$index" ng-repeat="repeat in results.myJsonResults">     <div id="$index" ng-click="saveID($index)" ng-repeat="subRepeat in results.myJsonResults.subresults"> </div> 

My problem is, when I click on my child div, I want to get my parent id name, but looks like angular doesn't set the ID properly to the div. Is it possible to set a dynamic ID in this concept?

PS: I tried, in the past, create a counter method on my controller and set an index, but it turns out that angular only recognizes the last value of this ID instead.

like image 487
marceloduende Avatar asked Mar 08 '13 19:03

marceloduende


People also ask

What is Ng-repeat?

Definition and Usage. The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

How do you pass an index in NG-repeat?

Each ng-repeat creates a child scope with the passed data, and also adds an additional $index variable in that scope. So what you need to do is reach up to the parent scope, and use that $index .

What is $Index in AngularJS?

Stay on the bleeding edge of your favorite technologies. $index is a way to show which iteration of a loop you're in. If we set up an ng-repeat to repeat over the letters in 'somewords', like so: <div ng-app="app"> <div ng-repeat="item in 'somewords'.split('')"> {{$index + 1}}.


1 Answers

To answer your question, try this:

<div id="{{$index}}" ...> 

While the above should work, this might be not what you want really (!). Please note that this is rather rare with AngularJS to manipulate elements by referring those by id.

You should focus on your model, declarative describe UI and let AngularJS do the rest without doing low-level DOM manipulations "by hand".

like image 52
pkozlowski.opensource Avatar answered Oct 03 '22 02:10

pkozlowski.opensource