ngRepeat – 限制显示结果的数量

我是一个巨大的AngularJS n00b,我甚至发现教程很难理解。 本教程通过构build一个显示手机的应用程序来帮助我。 我在第5步 ,我想作为一个实验,我试图让用户指定他们想显示多less。 该视图看起来像这样:

<body ng-controller="PhoneListCtrl"> <div class="container-fluid"> <div class="row-fluid"> <div class="span2"> <!--Sidebar content--> Search: <input ng-model="query"> How Many: <input ng-model="quantity"> Sort by: <select ng-model="orderProp"> <option value="name">Alphabetical</option> <option value="age">Newest</option> </select> </div> <div class="span10"> <!--Body content--> <ul class="phones"> <li ng-repeat="phone in phones | filter:query | orderBy:orderProp"> {{phone.name}} <p>{{phone.snippet}}</p> </li> </ul> </div> </div> </div> </body> 

我已经添加了这一行,用户可以input他们想要显示的结果数量:

 How Many: <input ng-model="quantity"> 

这是我的控制器:

 function PhoneListCtrl($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data.splice(0, 'quantity'); }); $scope.orderProp = 'age'; $scope.quantity = 5; } 

重要的路线是:

 $scope.phones = data.splice(0, 'quantity'); 

我可以用数字硬编码来表示应该显示多less个电话。 如果我放5,将显示5。 我所要做的就是从视图中读取该input中的数字,并将其放入data.splice行中。 我已经试过,没有报价,也没有工作。 我该怎么做呢?

稍微更“angular度的方式”将是使用直接的limitTofilter,由Angular原生提供:

 <ul class="phones"> <li ng-repeat="phone in phones | filter:query | orderBy:orderProp | limitTo:quantity"> {{phone.name}} <p>{{phone.snippet}}</p> </li> </ul> 
 app.controller('PhoneListCtrl', function($scope, $http) { $http.get('phones.json').then( function(phones){ $scope.phones = phones.data; } ); $scope.orderProp = 'age'; $scope.quantity = 5; } ); 

PLUNKER

晚会有点晚,但是这对我有用。 希望别人觉得它有用。

 <div ng-repeat="video in videos" ng-if="$index < 3"> ... </div> 

最初存储所有数据

 function PhoneListCtrl($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data.splice(0, 5); $scope.allPhones = data; }); $scope.orderProp = 'age'; $scope.howMany = 5; //then here watch the howMany variable on the scope and update the phones array accordingly $scope.$watch("howMany", function(newValue, oldValue){ $scope.phones = $scope.allPhones.splice(0,newValue) }); } 

编辑已经意外地把手表放在控制器之外,应该在里面。

如果你有对象或multidimensional array,这在我的情况下效果会更好。 它只会显示第一项,其他的只会在循环中被忽略。

 .filter('limitItems', function () { return function (items) { var result = {}, i = 1; angular.forEach(items, function(value, key) { if (i < 5) { result[key] = value; } i = i + 1; }); return result; }; }); 

改变5你想要什么。

使用limitTo过滤可以在ng-repeat中显示有限数目的结果。

 <ul class="phones"> <li ng-repeat="phone in phones | limitTo:5"> {{phone.name}} <p>{{phone.snippet}}</p> </li> </ul> 

另一个(我认为更好)的方法是实际拦截数据。 limitTo是好的,但是如果你的数组实际上包含数千的时候限制为10呢?

当拨打我的服务时,我只是这样做了:

 TaskService.getTasks(function(data){ $scope.tasks = data.slice(0,10); }); 

这限制了发送到视图的内容,因此性能要比在前端执行要好得多。