Reputation: 4062
I have the following directive (sales.jade
):
div(ng-repeat='product in products')
div.col-md-4
button.btn.btn-block.sell-button(id='{{product._id}}' role='button' ng-click='sell()'){{product.name}}
div(ng-repeat='p in supp track by $index | limitTo: 3')
p {{p.name}}
JS:
app.directive('sales', ['productServices', 'flash',
function(productServices, flash) {
var controller = function($scope, $timeout) {
productServices.getProducts()
.success(function(result) {
$scope.products = result.data
$scope.supp = []
})
.error(showErrorMessage(flash))
$scope.sell = function() {
that = this
$scope.supp.push(this.product)
$timeout(function() {
$('#' + that.product._id).blur()
}, 40)
}
}
return {
restrict: 'E',
templateUrl: '/partials/sales',
controller: controller
}
}
])
As you can see, when a button is clicked (that is tied to a product) I add that product to the supp
array and I am displaying the content of the supp
array through an ngRepeat
directive. My problem is, that the limitTo
filter is not applied all the time I add an element the supp
array. Thus the ngRepeat
displays all the items in supp
. How can I display only the last 3 elements of the supp
array, even if I add some new items to it?
Upvotes: 1
Views: 657
Reputation: 123739
If you need to show last 3 items then you need to use negative track by value. Also if you want to apply limit then set track by on the limit filter, basically you want to apply tracking on the actual limit (limitTo
) and not on the entire list (``supp`). Which is why it is showing all the elements in the list. i.e do:-
<div ng-repeat="p in supp | limitTo: -3 track by $index">
or with your template
div(ng-repeat='p in supp | limitTo: -3 track by $index')
Upvotes: 1