使用ngRepeat时限制显示结果的数量 [英] Limiting number of displayed results when using ngRepeat

查看:102
本文介绍了使用ngRepeat时限制显示结果的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 AngularJS教程很难理解;这一步引导我逐步构建一个可显示手机的应用程序.我正在步骤5 上,我认为作为实验,我将尝试允许用户指定要显示的数量.该视图如下所示:

I find the AngularJS tutorials hard to understand; this one is walking me through building an app that displays phones. I’m on step 5 and I thought as an experiment I’d try to allow users to specify how many they’d like to be shown. The view looks like this:

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

我添加了以下行,用户可以在其中输入他们想要显示多少个结果:

I’ve added this line where users can enter how many results they want shown:

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');

我可以硬编码一个数字以表示应该显示多少个电话.如果输入5,将显示5.我要做的就是从视图中读取该输入中的数字,并将其放在data.splice行中.我尝试使用带引号和不带引号的方法,但均无济于事.我该怎么做?

I can hard-code in a number to represent how many phones should be shown. If I put 5 in, 5 will be shown. All I want to do is read the number in that input from the view, and put that in the data.splice line. I’ve tried with and without quotes, and neither work. How do I do this?

推荐答案

稍微有点"Angular方式"是使用Angular原生提供的简单的limitTo过滤器:

Slightly more "Angular way" would be to use the straightforward limitTo filter, as natively provided by 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

这篇关于使用ngRepeat时限制显示结果的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆