Way to ng-repeat defined number of times instead o

2018-12-31 15:15发布

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 up 5 times assuming $scope.number equal to 5 in addition incrementing the number so each list item increments like 1, 2, 3, 4, 5

Desired result:

<ul>
   <li><span>1</span></li>
   <li><span>2</span></li>
   <li><span>3</span></li>
   <li><span>4</span></li>
   <li><span>5</span></li>
</ul>

25条回答
余欢
2楼-- · 2018-12-31 16:01

If n is not too high, another option could be to use split('') with a string of n characters :

<div ng-controller="MainCtrl">
<div ng-repeat="a in 'abcdefgh'.split('')">{{$index}}</div>
</div>
查看更多
宁负流年不负卿
3楼-- · 2018-12-31 16:03

you can do this:

<div ng-repeat="i in [1, 2, 3, 4]">
  ...
</div>
查看更多
呛了眼睛熬了心
4楼-- · 2018-12-31 16:04

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">
查看更多
素衣白纱
5楼-- · 2018-12-31 16:04

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.

查看更多
裙下三千臣
6楼-- · 2018-12-31 16:06

I wanted to keep my html very minimal, so defined a small filter that creates the array [0,1,2,...] as others have done:

angular.module('awesomeApp')
  .filter('range', function(){
    return function(n) {
      var res = [];
      for (var i = 0; i < n; i++) {
        res.push(i);
      }
      return res;
    };
  });

After that, on the view is possible to use like this:

<ul>
  <li ng-repeat="i in 5 | range">
    {{i+1}} <!-- the array will range from 0 to 4 -->
  </li>
</ul>
查看更多
不流泪的眼
7楼-- · 2018-12-31 16:07

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>
查看更多
登录 后发表回答