是否有一种方法可以ng-repeat定义的次数,而不是总是要迭代一个数组?

例如,下面我希望列表项显示5次,假设为$scope。数字等于5,加上增加的数字,所以每个列表项都增加,如1,2,3,4,5

预期的结果:

<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>

当前回答

最简单的答案:2行代码

JS(在你的AngularJS控制器中)

$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>

...其中repeatCount是应该出现在该位置的重复次数。

其他回答

Angular提供了一个非常可爱的函数slice..使用它你可以达到你想要的效果。 例如ng-repeat="ab in abc.slice(startIndex,endIndex)"

这个演示:http://jsfiddle.net/sahilosheal/LurcV/39/将帮助你,并告诉你如何使用这个“让生活更简单”的功能。:)

html:

<div class="div" ng-app >
    <div ng-controller="Main">
        <h2>sliced list(conditional NG-repeat)</h2>
        <ul ng-controller="ctrlParent">
            <li ng-repeat="ab in abc.slice(2,5)"><span>{{$index+1}} :: {{ab.name}} </span></li>
        </ul>
        <h2>unsliced list( no conditional NG-repeat)</h2>
         <ul ng-controller="ctrlParent">
            <li ng-repeat="ab in abc"><span>{{$index+1}} :: {{ab.name}} </span></li>
        </ul>

    </div>

CSS:

ul
{
list-style: none;
}
.div{
    padding:25px;
}
li{
    background:#d4d4d4;
    color:#052349;
}

ng-JS:

 function ctrlParent ($scope) {
    $scope.abc = [
     { "name": "What we do", url: "/Home/AboutUs" },
     { "name": "Photo Gallery", url: "/home/gallery" },
     { "name": "What we work", url: "/Home/AboutUs" },
     { "name": "Photo play", url: "/home/gallery" },
     { "name": "Where", url: "/Home/AboutUs" },
     { "name": "playground", url: "/home/gallery" },
     { "name": "What we score", url: "/Home/AboutUs" },
     { "name": "awesome", url: "/home/gallery" },
     { "name": "oscar", url: "/Home/AboutUs" },
     { "name": "american hustle", url: "/home/gallery" }
    ];
}
function Main($scope){
    $scope.items = [{sort: 1, name: 'First'}, 
                    {sort: 2, name: 'Second'}, 
                    {sort: 3, name: 'Third'}, 
                    {sort: 4, name:'Last'}];
    }

你可以使用ng-if指令和ng-repeat

因此,如果num是元素需要重复的次数:

<li ng-repeat="item in list" ng-if="$index < num">

由于遍历字符串,它将为每个字符呈现一个项:

<li ng-repeat = "k in 'aaaa' track by $index">
   {{$index}} //THIS DOESN'T ANSWER OP'S QUESTION. Read below.
</li>

我们可以使用数字|小数点后n位本机过滤器来使用这个丑陋但没有代码的解决方案。

 <li ng-repeat="k in (0|number:mynumber -2 ) track by $index">
    {{$index}}
 </li>

这样我们就有了mynumber元素,而不需要额外的代码。说‘0.000’。 我们用mynumber - 2来补偿0。 对于低于3的数字,它将不起作用,但在某些情况下可能有用。

如果n不是太高,另一种选择是使用split(")对n个字符的字符串:

<div ng-controller="MainCtrl">
<div ng-repeat="a in 'abcdefgh'.split('')">{{$index}}</div>
</div>

对于使用CoffeeScript的用户,您可以使用范围理解:

指令

link: (scope, element, attrs) ->
  scope.range = [1..+attrs.range]

或控制器

$scope.range = [1..+$someVariable]
$scope.range = [1..5] # Or just an integer

模板

<div ng-repeat="i in range">[ the rest of your code ]</div>