【问题标题】:simple filter out objects with a certain property integer value angular简单过滤出具有特定属性整数值 angular 的对象
【发布时间】:2016-09-22 08:38:45
【问题描述】:

我想过滤掉所有数量小于 1 的对象,我必须制作一个自定义过滤器才能实现这一点。我希望有一个比自定义过滤器更简单的解决方案。

以下将不起作用

<tr ng-repeat="product in products | filter: {quantity: '!0'}">

这将过滤掉 10,20 等等,除了 0。

我最终使用了这个自定义过滤器:

app.filter('quantityFilter', function() {
  return function( products) {
    var filtered = [];
    angular.forEach(products, function(product) {
        if(product.quantity > 0 ){
            filtered.push(product);
        }
    });
    return filtered;
  };
});

HTML:

<tr ng-repeat="product in products | quantityFilter">

有没有更流畅的解决方案?喜欢(不起作用):

<tr ng-repeat="product in products | filter: {quantity: >0}">

【问题讨论】:

标签: javascript angularjs angularjs-ng-repeat angularjs-filter


【解决方案1】:

您可以为过滤器使用谓词函数,而不是编写单独的过滤器。这在 AngularJS documentation 中有详细描述。

所以对你来说,这变成了:

<tr ng-repeat="product in products | filter:noZeroQuantity">

在控制器中:

$scope.noZeroQuantity = function(value, index, array) {
    return value.quantity !== 0;
}

我在jsfiddle写了一个例子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 2016-07-19
    • 2014-08-19
    • 2015-03-25
    • 2021-12-08
    • 2015-07-03
    • 2018-11-08
    相关资源
    最近更新 更多