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

<div ng-repeat="repeat in results.myJsonResults"> <div 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.

1

4 Answers

To answer your question, try this:

<div ...> 

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".

9

A use case I can think of is associating <label> elements with their respective <input> elements, as seen in

Applied there is a pkozlowski.opensource's method

<label for="{{ 'textField-' + $index }}">Option {{ $index }}</label> <input type="text" ng-model="field"/> 

Though I'm unsure if this is the most effective method. (Even if only for readability)

2
<div ...> 

Works well, but you can also put a dynamic id with the field repeated if - for instance - subRepeat would have an id field. That would be:

<div ...> 

That will put ids like subRepeat1, subRepeat2, ... on your repeated div

you need to hold the index in your objects

results = { myJsonResults : [ { name: "abc", id: 1, subResults: [ { subName: "123", id: 1 }, { subName: "456", id: 2 }] } { name: "xyz", id: 2, subResults: [ { subName: "789", id: 1 }, { subName: "098", id: 2 }] } ] }; 

Also your repeat refers to results, which disconnects them, instead use thisResult:

<div ng-repeat="thisResult in results.myJsonResults"> {{ thisResult.name }} <div ng-click="saveID(subResult.id)" ng-repeat="subResult in thisResult.subResults"> {{ subResult.subName }} </div> </div> 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy