Thursday, 16 March 2017

How to use index and parent index in nested ng-repeat ?


$index and $parent.$index
$index  
<body ng-app="module1"> <div ng-controller="myController"> 
  <ul>
     <li ng-repeat="course in courses">
         {{ $index }} {{ course.name }}

         <ul>
           <li ng-repeat="subject in course.subjects">
               
{{ $index }} {{ subject.name }}
           </li>
         </ul>

     </li>
  </ul>
</div>
 
OUTPUT
  • 0 BCA
    • 0 Fundamentals
    • 1 C
    • 2 C++
  • 1 MCA
    • 0 Java
    • 1 VB
    •     ...

$parent.$index  
<body ng-app="module1">
  <div ng-controller="myController"> 
  <ul>
     <li ng-repeat="course in courses">
        
{{ $index }} {{ course.name }}
         <ul>
           <li ng-repeat="subject in course.subjects">
               
{{ $parent.$index }} {{ $index }} {{ subject.name }}
           </li>
         </ul>

     </li>
  </ul>
</div> 

OUTPUT
  • 0 BCA
    • 0 0 Fundamentals
    • 0 1 C
    • 0 2 C++
  • 1 MCA
    • 1 0 Java
    • 1 1 VB
    •     ...


Using ng-init  
<body ng-app="module1"> <div ng-controller="myController"> 
  <ul>
     <li ng-repeat="course in courses"  ng-init="parentIdx=$index">
        
{{ $index }} {{ course.name }}
         <ul>
           <li ng-repeat="subject in course.subjects">
               
{{ parentIdx }} {{ $index }} {{ subject.name }}
           </li>
         </ul>

     </li>
  </ul>
</div> 

OUTPUT
  • 0 BCA
    • 0 0 Fundamentals
    • 0 1 C
    • 0 2 C++
  • 1 MCA
    • 1 0 Java
    • 1 1 VB
    •     ...

No comments:

Post a Comment

Note: only a member of this blog may post a comment.