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

前端 未结 26 3180
刺人心
刺人心 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:18

    This is really UGLY, but it works without a controller for either an integer or variable:

    integer:

    <span ng-repeat="_ in ((_ = []) && (_.length=33) && _) track by $index">{{$index}}</span>
    

    variable:

    <span ng-repeat="_ in ((_ = []) && (_.length=myVar) && _) track by $index">{{$index}}</span>
    
    0 讨论(0)
  • 2020-11-22 15:18

    Heres an answer for angular 1.2.x

    Basically it is the same, with the slight modification of of the ng-repeat

    <li ng-repeat="i in getNumber(myNumber) track by $index">
    

    here is the fiddle: http://jsfiddle.net/cHQLH/153/

    this is because angular 1.2 doesn't allow duplicate values in the directive. This means if you are trying to do the following, you will get an error.

    <li ng-repeat="x in [1,1,1]"></li>
    
    0 讨论(0)
  • 2020-11-22 15:18
    $scope.number = 5;
    
    <div ng-repeat="n in [] | range:$scope.number">
          <span>{{$index}}</span>
    </div>
    
    0 讨论(0)
  • 2020-11-22 15:19

    You can use this example.

    Inside controller:

    $scope.data = {
        'myVal': 33,
        'maxVal': 55,
        'indexCount': function(count) {
            var cnt = 10;
            if (typeof count === 'number') {
                cnt = count;
            }
            return new Array(cnt);
        }
    };
    

    Example for select element at the HTML code side:

    <select ng-model="data.myVal" value="{{ data.myVal }}">
        <option ng-repeat="i in data.indexCount(data.maxVal) track by $index" value="{{ $index + 1 }}">{{ $index + 1 }}</option>
    </select>
    
    0 讨论(0)
  • 2020-11-22 15:20

    Here is an example of how you could do this. Note that I was inspired by a comment in the ng-repeat docs: http://jsfiddle.net/digitalzebra/wnWY6/

    Note the ng-repeat directive:

    <div ng-app>
        <div ng-controller="TestCtrl">
            <div ng-repeat="a in range(5) track by $index">{{$index + 1}}</div>
        </div>
    </div>
    

    Here is the controller:

    function TestCtrl($scope) {
        $scope.range = function(n) {
            return new Array(n);
        };
    };
    
    0 讨论(0)
  • 2020-11-22 15:23

    I ran into the same issue. I came across this thread, but didn't like the methods they had here. My solution was using underscore.js, which we had already installed. It's as simple as this:

    <ul>
        <li ng-repeat="n in _.range(1,6)"><span>{{n}}</span></li>
    </ul>
    

    This will do exactly what you're looking for.

    0 讨论(0)
提交回复
热议问题