【问题标题】:Angular multiple filter, second filter is empty?角度多重过滤器,第二个过滤器是空的?
【发布时间】:2016-08-23 07:49:13
【问题描述】:

我有一个 ng-repeat(玉):

.col-lg-4.col-md-4.col-sm-6.col-xs-12.product.product-grid(ng-repeat='item in collection | product_sex:filter_sex | product_stock:stockKind')

在我的 app.js 中有两个过滤器:

.filter('product_sex', function(){
    return function(input, sex){

        if(input == undefined){
            input = [];
        }
        var output = [];

        if(sex == 'undefined' || sex =='all'){
            output = input;
        }

            for(var i =0; i < input.length; i++){
                var item = input[i];

                if (item.product.sex == sex){
                    output.push(item);
                }
            }


        return output;
    }
})
.filter('product_stock', function(){
    return function(input, stockKind){

        if(input == 'undefined'){
            input = [];
        }

        var output = [];

        if (stockKind == 'undefined' || stockKind == 'all'){
            output = input;
        }

            for(var i=0; i< input.length; i++){
                var item = input[i];

                if(item.stock < 0 && item.status != 'Niet leverbaar' && stockKind == 'online'){
                    output.push(item);
                }else if(item.stock > 0 && item.status != 'Niet leverbaar' && stockKind =='fysiek'){
                    output.push(item);
                }
            }


    }
})

我想将这两个过滤器都应用到我的 ng-repeat。第一个过滤器工作正常,但是当我添加第二个过滤器(如示例中)时,它不会返回任何内容。角度错误日志显示TypeError: Cannot read property 'length' of undefined 用于product_stock filter 中的for 循环。我看不出我做错了什么,所以我想知道您是否可以再次帮助我?

在我的控制器中,我将$scope.stockKind$scope.filter_sex 填充为“全部”。后来我可以在单击链接时更改它的值,例如ng-click='stockKind="online"'

【问题讨论】:

  • 调试您的代码并检查您的input 过滤器中input 的内容

标签: javascript angularjs


【解决方案1】:

您的错误出现在代码的以下部分

if(input == 'undefined'){
    input = [];
}

你应该把它替换为

if(input == null){
    input = [];
}

if(input === undefined || input === null){
    input = [];
}

两者完全相同

【讨论】:

  • 您确定 OP 期望的是 undefined“值”而不是字符串 'undefined'
  • 此外undefined不是关键字。要对其进行测试,您最好使用以下测试:typeof === 'undefined'。见stackoverflow.com/a/3550319/1153988
  • 不确定,但他是为其他过滤器做到的
  • ...或更简单的if(!input)
  • 是的,他做了以下测试if(sex == 'undefined' || sex =='all') 所以我认为'undefined' 和'all' 是sex 的可能值,因为'male' 和'female' 肯定是。跨度>
猜你喜欢
  • 2021-05-03
  • 1970-01-01
  • 2015-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多