在AngularJS中限制ng-repeat迭代



我嵌套了像这样的ng-repeat。我想限制它只使用列表中的前两个项目(不是完整的列表)。

ng-repeat = "items in phone.comments 

和HTML:

      <div class="wallList clearfix" ng-repeat = "items in phone.comments | limitTo:quantity">
        <div class="wallListImage">
          <a href="#">
            <img ng-show = "items.imageUrl" ng-src="{{items.imageUrl}}" height = "42px" width= "42px"/>
            <img ng-show = "!items.imageUrl" ng-src="WishlistImage/movies.png" height = "42px" width= "42px"/>
          </a>
        </div>
      </div>

看来你选对了方向。假设您已经定义了$作用域。数量,你的代码应该可以工作。就像您在示例中一样,我建议使用'limitTo'过滤器。

使用示例:

<div ng-repeat="item in items | limitTo:2">

你可以在这里看到一个活生生的例子:

http://jsfiddle.net/Nu7rZ/

这里有一个类似的Stack Overflow问题:

方法ng重复定义的次数,而不是重复数组?

您可以在ng-repeat语句中显式地使用:

ng-repeat="items in phone.comments.slice(0,2)"

JavaScript slice函数接受开始(包含)和结束(不包含)数组索引,因此上面将给出前两项。

参见http://jsfiddle.net/spikeheap/9fBvT/获得一个工作示例。有关slice的更多信息,请参见http://www.w3schools.com/jsref/jsref_slice_array.asp。

您可能想要考虑将切片移动到控制器中,但这取决于您的用例和个人偏好。

最新更新