javascript - AngularJS limitTo 动态扩展数组

标签 javascript arrays angularjs

我有以下指令( 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/

相关文章:

ruby - 如何使用 Ruby 从文件加载数组?

arrays - Bash 解析动态数组并将特定值存储在另一个

javascript - 从 nginclude 调用父作用域上的函数

javascript - 如何触发到达页面中特定div的事件滚动

javascript - 过滤 View 时需要 ng-repeat 过滤器来忽略任何超链接字符串值

javascript - 如何使 map 开启器显示全高?

javascript - 功能被提升。 fun1 调用 fun2。他们以什么顺序声明?

javascript - mongodb/mongoose - 使用 $ 运算符更新会丢失 _id

javascript - 使用 ngFor 遍历二维数组

javascript - tsc命令输出空js文件