In the previous post: AngularJS- What are the directives in AngularJS?, we have discussed several AngularJS directives. In the following example, you can learn the real use of the ng-repeat directive. The example draw the maths times tables for the number two to ten.
The below example draws the following output on the web page.
See the full code(using of the ng-repeat directive) of the html web page .
<!DOCTYPE html> <html> <head> </head> <body> <h2>Example of ng-repeat directive- Create Tables</h2> <div ng-app="" ng-init="nums=[1,2,3,4,5,6,7,8,9,10]; digits = [2,3,4,5,6,7,8,9,10]"> <div ng-repeat="y in digits" style="float:left"> <ul> <li ng-repeat="x in nums"> {{y}} * {{x}} = {{y * x }} </li> </ul> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html>
Edit with Plunker (Test your self)
The ng-repeat directive behaves like the for each loop statement where we repeat the execution of a particular portion for each element in the collection. In the above example I am using the nested ng-repeat directives to display the maths times table on the page.
More on the ng-repeat
There are the following properties in the local scope of each template instance you can use.
$index
You get the index of the iteration in the ngrepeat template by using the {{$index}} expression like as:
<li ng-repeat="x in nums"> Position {{$index}} : {{y}} * {{x}} = {{y * x }} </li>
$first, $middle and $last
You can determine the following by these properties:
$first : true if the repeated element is first in the iterator.
$middle: true if the repeated element is between the first and last in the iterator.
$last: true if the repeated element is last in the iterator.
$even and $odd
You can easily determine that the iteration is even or odd with the help of $even and $odd properties. If $index is even then $even will be true otherwise false. And if $index is odd then $odd will be true otherwise false.
See the following example:
<div ng-app="" ng-init="nums=[1,2,3,4,5,6,7,8,9,10]"> <ul> <li ng-repeat="x in nums" style="text-decoration:none"> <span ng-if=$even>Row is even</span> <span ng-if=$odd>Row is odd</span> </li> </ul> </div>
In the next article we will learn that how to use the controller to display the above example.