【问题标题】:Angularjs Filter not working when the property is undefined属性未定义时Angularjs过滤器不起作用
【发布时间】:2015-12-18 09:38:08
【问题描述】:

我有以下设置

  $scope.array = 
    [
      {propertyA: "test", 
       propertyB: {
                   propertyC: [true, true, false]
                  }
      },
      {propertyA: "test2"},
      {propertyA: "test3"}
    ]

然后

<div ng-repeat="item in array| filter :{propertyB: ''} :true">
     {{item.propertyA}}
</div>

所以问题是:

  1. 此设置不显示任何内容

  2. 如果我更改为|filter :{propertyB: '!!'} :true,它不会显示任何内容

  3. 如果我更改为|filter :{propertyB: undefined} :true,它会显示所有内容

我想不通。

目标:我想显示未定义 propertyB 的项目,在其他情况下则相反。

编辑 1:如果我使用 angular.equals(item.propertyB, undefined) 遍历数组,我会得到 false, true, true

编辑 2:jsfiddle UPDATED

编辑3:我已经更新了问题

【问题讨论】:

标签: javascript angularjs angularjs-filter


【解决方案1】:
$scope.array = 
[
  {propertyA: "test", propertyB: "test2"},
  {propertyA: "test2"},
  {propertyA: "test3"}
];
$scope.filteredArray =[];
angular.forEach($scope.array,function(eachData){
   if(angular.isUndefined(eachData.propertyB))
   $scope.filteredArray.push(eachData);
});

$scope.filteredArray 是你想要的数组,你可以重复使用它来绑定 html。

【讨论】:

    【解决方案2】:

    您在ng-repeat 上添加filter,因此您将获得collection,作为过滤器的输入,而不是单个数组元素,因此您的实现将无法正常工作。

    正如 Kunal 所说,尝试事先过滤数组并在过滤后的数组上重复。 或在双花括号 {{}} 内添加过滤器。

    检查这个plnkr

    【讨论】:

    • 请查看更新后的问题。我还想在渲染元素之前过滤元素(在 ng-repeat 中)
    【解决方案3】:

    我最终这样做了。

    .filter('undefinedProperties', ['$filter', function ($filter) {
            var checkProperty = function (property, returnUndefined) {
                if (returnUndefined) {
                    if (property !== undefined) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    if (property === undefined) {
                        return true;
                    } else {
                        return false;
                    }
                }
            };
            return function (input, propertyArray, returnUndefined) {
                if (angular.isArray(propertyArray)) {
                    if (angular.isArray(input) && input.length > 0) {
                        angular.forEach(propertyArray, function (property) {
                            for (var i = input.length; i-- > 0;) {
                                if (checkProperty(input[i][property], returnUndefined)) {
                                    input.splice(i, 1);
                                }
                            }
                        });
                    }
                    return input;
                } else {
                    throw "PropertyArray is not an array";
                }
            };
        }])
    

    【讨论】:

      猜你喜欢
      • 2017-08-16
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多