javascriptangularjsangular-ui-tree

How to get the key value or iteration of a certain item in angular ui tree?


I have a piece of code which is a basic example of how to use angular-ui-tree:

<div ui-tree>
  <ol ui-tree-nodes="" ng-model="list">
    <li ng-repeat="item in list" ui-tree-node>
      <div ui-tree-handle>
        {{item.title}}
      </div>
      <ol ui-tree-nodes="" ng-model="item.items">
        <li ng-repeat="subItem in item.items" ui-tree-node>
          <div ui-tree-handle>
            {{subItem.title}}
          </div>
        </li>
      </ol>
    </li>
  </ol>
</div>

Now if I have an {{item}}, is there a way to get the item's iteration on the loop? Like for example I want to get a condition that if this item's current loop iteration is an odd number or an even number for instance, I could change the style of the certain node of the tree like say I have an alternate blue and red items based on its iteration if it's odd or even.


Solution

  • You can use $index in your ng-repeat loop it will give you the interation number-

    ng-class="{ even : $index%2 == 0, odd : $index%2 != 0 }"
    

    CSS

    .even {
        color: blue;
    }
    .odd {
        color: red;
    }
    

    Final code

       <div ui-tree>
            <ol ui-tree-nodes="" ng-model="list">
                <li ng-repeat="item in list" ui-tree-node>
                    <div ui-tree-handle>
                        {{item.title}}
                    </div>
                    <ol ui-tree-nodes="" ng-model="item.items">
                        <li ng-repeat="subItem in item.items" ui-tree-node>
                            <div ui-tree-handle ng-class="{ even : $index%2 == 0, odd : $index%2 != 0 }">
                                {{subItem.title}}
                            </div>
                        </li>
                    </ol>
                </li>
            </ol>
        </div>