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

How to Implement Fixed-Length ng-repeat in AngularJS?

Linda Hamilton
Release: 2024-10-26 19:44:29
Original
747 people have browsed it

How to Implement Fixed-Length ng-repeat in AngularJS?

Alternative Approaches for Fixed-Length ng-repeat

In AngularJS, ng-repeat typically operates on arrays. However, there are situations where you need to repeat elements a fixed number of times. Here are two possible approaches:

Option 1: Using a Custom Function

If you are using an older version of AngularJS (prior to 1.3.0), you can define a function that returns an array of the desired length:

<code class="html"><li ng-repeat="i in getNumber(number)">
    <span>{{ $index+1 }}</span>
</li></code>
Copy after login
<code class="javascript">$scope.getNumber = function(num) {
    return new Array(num);   
}</code>
Copy after login

Option 2: Using the Constructor Property (AngularJS 1.3.0 and above)

For newer versions of AngularJS, you can leverage the Array.constructor property without the need for a function:

<code class="html"><li ng-repeat="x in [].constructor(number) track by $index">
    <span>{{ $index+1 }}</span>
</li></code>
Copy after login

The above is the detailed content of How to Implement Fixed-Length ng-repeat 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!