dynamic id ng-repeat

后端 未结 4 508
伪装坚强ぢ
伪装坚强ぢ 2020-12-30 18:38

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

相关标签:
4条回答
  • 2020-12-30 19:06

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

    0 讨论(0)
  • 2020-12-30 19:23
    <div id="{{$index}}" ...>
    

    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 id="subRepeat{{subRepeat.id}}" ...>
    

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

    0 讨论(0)
  • 2020-12-30 19:25

    A use case I can think of is associating <label> elements with their respective <input> elements, as seen in http://jsfiddle.net/YqUAp/

    Applied there is a pkozlowski.opensource's method

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

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

    0 讨论(0)
  • 2020-12-30 19:25

    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 id="thisResult.id" ng-repeat="thisResult in results.myJsonResults">
        {{ thisResult.name }}
        <div id="subResult.id" ng-click="saveID(subResult.id)" ng-repeat="subResult in thisResult.subResults"> {{ subResult.subName }} </div>
    </div>
    
    0 讨论(0)
提交回复
热议问题