Iteration ng-repeat only X times in AngularJs

前端 未结 7 1886
悲哀的现实
悲哀的现实 2020-11-28 04:08

How can I use ng-repeat like for in Javascript?

example:

Text

I want to iterate wit

相关标签:
7条回答
  • 2020-11-28 04:35

    Angular comes with a limitTo:limit filter, it support limiting first x items and last x items:

    <div ng-repeat="item in items|limitTo:4">{{item}}</div>
    
    0 讨论(0)
  • 2020-11-28 04:37

    You can use slice method in javascript array object

    <div ng-repeat="item in items.slice(0, 4)">{{item}}</div>
    

    Short n sweet

    0 讨论(0)
  • 2020-11-28 04:38

    To repeat 7 times, try to use a an array with length=7, then track it by $index:

    <span ng-repeat="a in (((b=[]).length=7)&&b) track by $index" ng-bind="$index + 1 + ', '"></span>
    

    b=[] create an empty Array «b»,
    .length=7 set it's size to «7»,
    &&b let the new Array «b» be available to ng-repeat,
    track by $index where «$index» is the position of iteration.
    ng-bind="$index + 1" display starting at 1.

    To repeat X times:
    just replace 7 by X.

    0 讨论(0)
  • 2020-11-28 04:39

    This is the simplest workaround I could think of.

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

    Here's a Plunker example.

    0 讨论(0)
  • 2020-11-28 04:50

    Answer given by @mpm is not working it gives the error

    Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}

    To avoid this along with

    ng-repeat="t in getTimes(4)"

    use

    track by $index

    like this

    <div ng-repeat="t in getTimes(4) track by $index">TEXT</div>

    0 讨论(0)
  • 2020-11-28 04:51

    in the html :

    <div ng-repeat="t in getTimes(4)">text</div>
    

    and in the controller :

    $scope.getTimes=function(n){
         return new Array(n);
    };
    

    http://plnkr.co/edit/j5kNLY4Xr43CzcjM1gkj

    EDIT :

    with angularjs > 1.2.x

    <div ng-repeat="t in getTimes(4) track by $index">TEXT</div>
    
    0 讨论(0)
提交回复
热议问题