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

前端 未结 26 3720
刺人心
刺人心 2020-11-22 14:53

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

26条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 15:36

    Update (9/25/2018)

    Newer versions of AngularJS (>= 1.3.0) allow you to do this with only a variable (no function needed):

  • {{ $index+1 }}
  • $scope.number = 5;
    

    This was not possible at the time the question was first asked. Credit to @Nikhil Nambiar from his answer below for this update


    Original (5/29/2013)

    At the moment, ng-repeat only accepts a collection as a parameter, but you could do this:

  • {{ $index+1 }}
  • And somewhere in your controller:

    $scope.number = 5;
    $scope.getNumber = function(num) {
        return new Array(num);   
    }
    

    This would allow you to change $scope.number to any number as you please and still maintain the binding you're looking for.

    EDIT (1/6/2014) -- Newer versions of AngularJS (>= 1.1.5) require track by $index:

  • {{ $index+1 }}
  • Here is a fiddle with a couple of lists using the same getNumber function.

提交回复
热议问题