Home  >  Article  >  Web Front-end  >  How to Repeat Elements a Specific Number of Times in AngularJS?

How to Repeat Elements a Specific Number of Times in AngularJS?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 09:38:30801browse

How to Repeat Elements a Specific Number of Times in AngularJS?

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:

  1. Create a function in your controller called getNumber():
<code class="js">$scope.getNumber = function(num) {
    return new Array(num);   
}</code>
  1. In your HTML, use the getNumber() function in your ng-repeat to define the number of times to repeat:
<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn