AngularJS限制动态扩展数组

AngularJS limitTo on dynamically expanding array

本文关键字:扩展 数组 动态 AngularJS      更新时间:2023-09-26

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

正如您所看到的,当单击按钮(与产品绑定)时,我将该产品添加到supp数组中,并通过ngRepeat指令显示supp数组的内容。我的问题是,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