Repeating Elements a Specific Number of Times with AngularJS
When working with AngularJS, the ng-repeat directive is often used to iterate over arrays and display data dynamically. However, what if you need to repeat elements a specific number of times, regardless of any array?
Original Solution (pre-AngularJS 1.3.0)
For versions of AngularJS prior to 1.3.0, a workaround was required:
<code class="js">$scope.getNumber = function(num) { return new Array(num); }</code>
<code class="html"><li ng-repeat="i in getNumber(number) track by $index"> <span>{{ $index+1 }}</span> </li></code>
Updated Solution (AngularJS 1.3.0 and above)
Starting with AngularJS 1.3.0, the need for the getNumber() function is eliminated:
<code class="html"><li ng-repeat="x in [].constructor(number) track by $index"> <span>{{ $index+1 }}</span> </li></code>
Example Output
Assuming $scope.number is set to 5, the desired output will be rendered:
<code class="html"><ul> <li><span>1</span></li> <li><span>2</span></li> <li><span>3</span></li> <li><span>4</span></li> <li><span>5</span></li> </ul></code>
This technique allows you to dynamically repeat elements a specific number of times, providing greater flexibility in AngularJS template creation.
The above is the detailed content of How to Repeat Elements a Specific Number of Times in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!