I'm a huge AngularJS n00b and am finding even the tutorials hard to understand. This tutorial 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 that 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?
This works better in my case if you have object or multi-dimensional array. It will shows only first items, other will be just ignored in loop.
Change 5 on what you want.
Slightly more "Angular way" would be to use the straightforward
limitTo
filter, as natively provided by Angular:PLUNKER
Another (and I think better) way to achieve this is to actually intercept the data. limitTo is okay but what if you're limiting to 10 when your array actually contains thousands?
When calling my service I simply did this:
This limits what is sent to the view, so should be much better for performance than doing this on the front-end.
here is anaother way to limit your filter on html, for example I want to display 3 list at time than i will use limitTo:3
A little late to the party, but this worked for me. Hopefully someone else finds it useful.
store all your data initially
EDIT had accidentally put the watch outside the controller it should have been inside.