Explain Codes LogoExplain Codes Logo

Way to ng-repeat defined number of times instead of repeating over array?

javascript
ng-repeat
angularjs
performance
Nikita BarsukovbyNikita Barsukov·Oct 8, 2024
TLDR

AngularJS provides a robust way to accomplish this with the framework's ng-repeat directive and a custom filter:

<div ng-repeat="i in [] | range:5"> <!-- The magic 5 repeating times --> {{ i + 1 }} </div>

Add the range filter in your AngularJS application:

app.filter('range', () => (input, total) => Array.from({ length: total }, (_, i) => i));

This AngularJS filter generates an array from 0 to 4, and the ng-repeat directive iterates over it, repeating the HTML element 5 times.

Short 'n sweet, post-1.3.0 style

In AngularJS versions 1.3.0 and later, a more streamlined snippet to ng-repeat a set number of times comes in handy - less code, more output:

<div ng-repeat="i in [].constructor(5) track by $index"> <!-- Here's to our love for repetition! --> </div>

Repeat after me

You can define the number of repetitions dynamically using $scope.number in your controller. This gives you maximum flexibility:

$scope.number = 5; // Configuration control, at your service!
<div ng-repeat="x in [].constructor(number) track by $index"> {{ $index + 1 }} </div>

Don't forget the track by $index to ensure your DOM rides smoothly when the list morphs.

Rolling back to good old days, pre-1.3.0 style

For those using AngularJS versions before 1.3.0 - we've got your back. Whip up a custom scope function and you're good to go:

// Because, who doesn't love a good ol' array? $scope.getNumber = function(num) { return new Array(num); };
<div ng-repeat="n in getNumber(number)"> {{ $index + 1 }} </div>

Unleashing the ng-repeat beast

Fusion-dancing with filters

Team up ng-repeat with limitTo filter, a classic move:

<div ng-repeat="i in [].constructor(10) | limitTo: number track by $index"> <!-- Repeating, in style! BOOM! 💥 --> {{ $index + 1 }} </div>

Construct'n roll

Put the constructor to work, inline and independent:

<div ng-repeat="n in [].constructor(5)"> <!-- Unleashing the constructor power! --> </div>

Who needs additional scope functions or controllers? Less is more!

Code gymnastics

Dynamic content juggling

Juggle dynamic content within ng-repeat with agility:

<div ng-repeat="n in [].constructor(number) track by $index"> {{ dynamicContent[n] }} </div>

Existing $scope values backing your loop, smooth!

On-the-go repeats

Adapt the ng-repeat count via state changes:

// Because, who doesn't crave for control? $scope.adjustNumber = function(newCount) { $scope.number = newCount; };

ng-repeat detects changes in $scope.number and transforms the list in real-time.

Tackling the giants

For the brave hearts handling large iterations:

<div ng-repeat="n in getVeryLargeNumber()"> <!-- Treachery ahead! Tread carefully! --> </div>

Infinite scroll or lazy loading - your safety gear against gruesome DOM consequences.