【问题标题】:angularjs filter in the controller where value isn't empty值不为空的控制器中的 angularjs 过滤器
【发布时间】:2018-11-11 20:34:23
【问题描述】:

我有一个 JSON 对象数组,我试图将列表过滤到仅存在特定字段值的对象。

我要过滤的字段几乎可以包含任何内容,因此除了存在值的位置之外,我无法真正寻找匹配的内容。

我需要在 angularjs 控制器中应用过滤器。

如果我对特定值(如“bob”)进行匹配,则以下内容有效,但并非所有对象都具有“newName”的值。

$scope.CorrectedNames = $filter('filter')($scope.dataList, { newName: 'bob' }).length;
console.log('Total Names to Update: '+$scope.totalCorrectedAccountNumbers.length);

我试过了

newName: '!'

这将返回零个结果。

newName: '!""'

这会返回整个 json 列表

它们是我通过搜索得出的仅有的 2 个想法。

字段值为空且不为NULL,否则我认为以下将起作用。

newName: '!=null' 

【问题讨论】:

  • 用js过滤器代替$filter怎么样?像 $scope.CorrectedNames = $scope.dataList.filter(x => x.newName === '');

标签: arrays angularjs json filter


【解决方案1】:

因此,您不想显示具有 newName 属性值为 null 或 nullstring 的对象。你应该使用纯js的.filter方法如下:

$scope.CorrectedNames = $scope.dataList.filter(function(a) {
    if(a.newName) {
    return a.newName.trim().length !== 0;
    }
});

通过在 $scope.CorrectedNames 数组中执行此操作,您将从 dataList 排除 newName 中的所有对象获得 null 或 nullstring 或没有 newName 属性的对象。

Plunker Demo

另一种方法是您可以创建自定义过滤器并在其实现中执行与上述相同的 .filter() 方法使用过滤。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多