Limiting number of displayed results when using ngRepeat

angularjs, javascript, model-view-controller, scope

Solution

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

Problem

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"> ``` Here’s my 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; } ``` The important line is: ``` $scope.phones = data.splice(0, 'quantity'); ``` 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?

Original source

Related problems