Traditionally, ng-repeat iterates over an array element, but there are instances where you might need to repeat a specific number of times. This article explores a convenient method to achieve just that.
Consider a scenario where you desire a list of items to display five times, incrementally numbered from 1 to 5. Instead of relying on an array, we can employ the following approach:
<code class="html"><li ng-repeat="i in getNumber(number) track by $index"> <span>{{ $index+1 }}</span> </li></code>
In your controller, the getNumber function will create an array of the desired length:
<code class="javascript">$scope.number = 5; $scope.getNumber = function(num) { return new Array(num); }</code>
For versions of AngularJS prior to 1.1.5, the above should suffice. However, from version 1.1.5 onwards, an additional track by $index attribute must be specified in the ng-repeat directive.
With this approach, you can dynamically alter $scope.number to any value, maintaining the desired number of iterations. This technique provides a convenient way to handle repetition in AngularJS applications.
The above is the detailed content of How can I repeat an element a specific number of times using ng-repeat in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!