Home  >  Article  >  Web Front-end  >  How to Implement Fixed-Length ng-repeat in AngularJS?

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 19:44:29748browse

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>
<code class="javascript">$scope.getNumber = function(num) {
    return new Array(num);   
}</code>

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>

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!

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