Is there a way to ng-repeat
a defined number of times instead of always having to iterate over an array?
For example, below I want the list item to show
You can use the ng-if
directive with ng-repeat
So, if num is the number of times you need the element repeated:
<li ng-repeat="item in list" ng-if="$index < num">
you can do this:
<div ng-repeat="i in [1, 2, 3, 4]">
...
</div>
JS (in your AngularJS controller)
$scope.range = new Array(MAX_REPEATS); // set MAX_REPEATS to the most repetitions you will ever need in a single ng-repeat that makes use of this strategy
HTML
<div ng-repeat="i in range.slice(0,repeatCount) track by $index"></div>
...where repeatCount
is the number of repetitions that should appear in this location.
since iterating over a string it will render an item for each char:
<li ng-repeat = "k in 'aaaa' track by $index">
{{$index}} //THIS DOESN'T ANSWER OP'S QUESTION. Read below.
</li>
we can use this ugly but no-code workaround using the number|n decimal places
native filter.
<li ng-repeat="k in (0|number:mynumber -2 ) track by $index">
{{$index}}
</li>
this way we'll have mynumber
elements with no extra code. Say '0.000'
.
We use mynumber - 2
to compensate 0.
It won't work for numbers below 3, but might be useful in some cases.
For users using CoffeeScript, you can use a range comprehension:
Directive
link: (scope, element, attrs) ->
scope.range = [1..+attrs.range]
or Controller
$scope.range = [1..+$someVariable]
$scope.range = [1..5] # Or just an integer
Template
<div ng-repeat="i in range">[ the rest of your code ]</div>
I think this jsFiddle from this thread might be what you're looking for.
<div ng-app ng-controller="Main">
<div ng-repeat="item in items | limitTo:2">
{{item.name}}
</div>
</div>