角度过滤器不显示具有null属性的对象

时间:2016-08-03 23:21:58

标签: angularjs filter

我有一系列像这样的运算符:

[  
   {  
      "id":1,
      "key":"55330",
      "name":"Macie",
      "operative_status":{  
         "id":20,
         "code":"100",
         "name_status":"viaje",
         "created_at":"2016-08-03T21:28:52Z"
      }
   },
   {  
      "id":2,
      "key":"8439",
      "name":"Darian",
      "operative_status":null
   },
   {  
      "id":3,
      "key":"49531",
      "name":"Kaelyn",
      "operative_status":null
   }
]

我希望使用ng-repeat

显示它们
<div ng-repeat="operator in operators | filter:{ operative_status : {name_status: status}}">

如您所见,我想按状态过滤。

问题是它没有显示operator_status为null的运算符。

2 个答案:

答案 0 :(得分:1)

对于您的数据,使用模式对象作为过滤器表达式不会起作用,因为null属性值为operative_status的项永远不会匹配,这就是你正在观察。

您可以使用谓词函数代替过滤器表达式。

例如:

$scope.filterByStatus = function (value) { if ($scope.status.length === 0) return true; return value.operative_status && value.operative_status.name_status === $scope.status; };

然后在过滤器表达式中使用它:

operator in operators | filter:filterByStatus

Demonstration Plunker

答案 1 :(得分:1)

要过滤null ,您必须执行以下操作:

<div ng-repeat="operator in operators | filter: { operative_status : search && {name_status: search } || '!'}">

<div ng-repeat="operator in operators | filter: { operative_status : search ? {name_status: search } : '!'}">

这是示例

(function() {
  "use strict";

  angular
    .module('app', [])
    .controller('MainCtrl', MainCtrl);

  MainCtrl.$inject = ['$scope'];

  function MainCtrl($scope) {
    $scope.operators = [  
       {  
          "id":1,
          "key":"55330",
          "name":"Macie",
          "operative_status":{  
             "id":20,
             "code":"100",
             "name_status":"viaje",
             "created_at":"2016-08-03T21:28:52Z"
          }
       },
       {  
          "id":2,
          "key":"8439",
          "name":"Darian",
          "operative_status":null
       },
       {  
          "id":3,
          "key":"49531",
          "name":"Kaelyn",
          "operative_status":null
       }
    ];
  }
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
</head>

<body ng-controller="MainCtrl">
  <input type="text" class="form-control" ng-model="search" placeholder="Search...">
  <hr>
  <div ng-repeat="operator in operators | filter: { operative_status : search && {name_status: search } || '!'}">
    <pre ng-bind="operator | json"></pre>
  </div>

</body>

</html>