我找到 AngularJS tutorials很难理解;这个正在引导我构建一个显示手机的应用程序。我在 step 5我想作为一个实验,我会尝试让用户指定他们希望显示多少。 View 如下所示:
<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>
我添加了这一行,用户可以在其中输入他们想要显示的结果数:
How Many: <input ng-model="quantity">
这是我的 Controller :
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');
我可以硬编码一个数字来表示应该显示多少部手机。如果我输入 5
,将显示 5。我要做的就是从 View 中读取该输入中的数字,并将其放在 data.splice
行中。我试过带引号和不带引号,都不管用。我该怎么做?
最佳答案
稍微更“Angular 方式”的是使用直接由 Angular 提供的 limitTo
过滤器:
<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;
}
);
关于javascript - 使用 ngRepeat 时限制显示结果的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17643361/