In AngularJS, the ng-repeat directive allows us to iterate over an array of elements. However, in certain scenarios, we may desire to repeat a specific template multiple times even in the absence of an array. This article addresses this need.
AngularJS prior to version 1.3.0 did not support direct iteration over a specified number of times. The workaround involved introducing a custom function and manipulating arrays.
Here's the modified ng-repeat syntax:
<code class="html"><li ng-repeat="i in getNumber(number) track by $index"> <span>{{ $index+1 }}</span> </li></code>
In your controller, define the getNumber function:
<code class="js">$scope.number = 5; $scope.getNumber = function(num) { return new Array(num); }</code>
This function returns an array of a specified length, simulating the behavior of iterating over an array.
Newer versions of AngularJS offer a simplified solution:
<code class="html"><li ng-repeat="x in [].constructor(number) track by $index"> <span>{{ $index+1 }}</span> </li></code>
This variation removes the need for a custom function.
Both methods provide a flexible and efficient way to iterate a defined number of times in AngularJS, enabling developers to create dynamic and adaptable user interfaces.
The above is the detailed content of How to Iterate a Defined Number of Times in AngularJS Without an Array?. For more information, please follow other related articles on the PHP Chinese website!