[英]AngularJS limitTo on dynamically expanding array
I have the following directive ( sales.jade
): 我有以下指令(
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: 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. 如您所见,当单击一个按钮(与产品相关联)时,我将该产品添加到
supp
数组中,并通过ngRepeat
指令显示supp
数组的内容。 My problem is, that the limitTo
filter is not applied all the time I add an element the supp
array. 我的问题是,在我向
supp
数组添加元素时,未limitTo
应用limitTo
过滤器。 Thus the ngRepeat
displays all the items in supp
. 因此,
ngRepeat
显示supp
所有项目。 How can I display only the last 3 elements of the supp
array, even if I add some new items to it? 即使我向其中添加一些新项目,如何仅显示
supp
数组的最后3个元素?
If you need to show last 3 items then you need to use negative track by value. 如果您需要显示最后3个项目,则需要使用负跟踪值。 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`). 同样,如果您想应用限制,然后在限制过滤器上设置跟踪依据,基本上您想将跟踪应用在实际限制(
limitTo
)而不是整个列表(``supp`'')上。 Which is why it is showing all the elements in the list. 这就是为什么它显示了列表中的所有元素。 ie 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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.