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

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

    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">
    
    0 讨论(0)
  • 2020-11-22 15:31

    you can do this:

    <div ng-repeat="i in [1, 2, 3, 4]">
      ...
    </div>
    
    0 讨论(0)
  • 2020-11-22 15:32

    Easiest answer: 2 lines of code

    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.

    0 讨论(0)
  • 2020-11-22 15:32

    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.

    0 讨论(0)
  • 2020-11-22 15:34

    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>
    
    0 讨论(0)
  • 2020-11-22 15:35

    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>
    
    0 讨论(0)
提交回复
热议问题