gpt4 book ai didi

javascript - AngularJS limitTo 动态扩展数组

转载 作者:行者123 更新时间:2023-11-28 01:04:37 26 4
gpt4 key购买 nike

我有以下指令( 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
}
}
])

如您所见,当单击按钮(与产品绑定(bind))时,我将该产品添加到 supp数组,我正在显示 supp 的内容数组通过 ngRepeat指示。我的问题是,limitTo当我添加元素 supp 时,过滤器不会一直应用。大批。因此ngRepeat显示 supp 中的所有项目。如何仅显示 supp 的最后 3 个元素数组,即使我向其中添加一些新项目?

最佳答案

如果您需要显示最后 3 项,则需要按值使用负跟踪。另外,如果您想应用限制,然后在限制过滤器上设置跟踪,基本上您希望对实际限制(limitTo)而不是整个列表(``supp`)应用跟踪。这就是为什么它显示列表中的所有元素。即:-

 <div ng-repeat="p in supp | limitTo: -3 track by $index">

或使用您的模板

 div(ng-repeat='p in supp | limitTo: -3 track by $index')

<强> Plnkr

关于javascript - AngularJS limitTo 动态扩展数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25230230/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com