Home > Web Front-end > JS Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-27 09:38:30
Original
799 people have browsed it

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>
Copy after login
  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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!