Way to ng-repeat defined number of times instead of repeating over array?
AngularJS provides a robust way to accomplish this with the framework's ng-repeat directive and a custom filter:
Add the range filter in your AngularJS application:
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:
Repeat after me
You can define the number of repetitions dynamically using $scope.number
in your controller. This gives you maximum flexibility:
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:
Unleashing the ng-repeat beast
Fusion-dancing with filters
Team up ng-repeat with limitTo filter, a classic move:
Construct'n roll
Put the constructor to work, inline and independent:
Who needs additional scope functions or controllers? Less is more!
Code gymnastics
Dynamic content juggling
Juggle dynamic content within ng-repeat
with agility:
Existing $scope
values backing your loop, smooth!
On-the-go repeats
Adapt the ng-repeat
count via state changes:
ng-repeat detects changes in $scope.number
and transforms the list in real-time.
Tackling the giants
For the brave hearts handling large iterations:
Infinite scroll or lazy loading - your safety gear against gruesome DOM consequences.
Was this article helpful?