Angular.js:通过不存在的键/值过滤ng-repeat

Angular.js: filter ng-repeat by absent key/value

本文关键字:过滤 ng-repeat 不存在 js Angular      更新时间:2023-09-26

我想过滤ng-repeat,以便它只显示所有键/值对都存在的行。

<div ng-app="myApp" ng-controller="oneController">
<table class="table table-bordered table-hover">
  <thead>
    <tr>
      <th>Country</th>
      <th>1960</th>
      <th>1970</th>
    </tr>
    <tbody>
      <tr ng-repeat="country in countries | orderBy: country.name">
        <td>{{country.name}}</td>
        <td>{{country.1960 | number}}</td>
        <td>{{country.1970 | number}}</td>
      </tr>
    </tbody>
</table>

Javascript

angular.module('myApp', []).
controller('oneController', function($scope) {
  $scope.countries = [
      {"name":"Aruba", "1960":"1567"},
     {"name":"Andorra","1960":77865,"1970":78360},
  ];
});

因此,在本例中,我不希望显示Aruba,只希望显示Andorra。

完整示例@ CSSDeck: http://cssdeck.com/labs/1aksiuuu(我不希望Aruba显示)

总是可以自定义过滤器:

<tr ng-repeat="country in countries | filter:allProperties | orderBy: country.name">

和过滤器

$scope.allProperties = function(item) {
    return item.name && item.1960 && item.1970
}

展开自定义过滤器的概念,我认为关键是您不知道任何给定对象可能缺少哪个属性。通过循环遍历所有对象中的所有属性,您可以创建至少存在于一个对象上的每个属性的主列表:

$scope.properties = function(){
  var props = [];    
  angular.forEach($scope.countries, function(country){
    for(var prop in country){
      if(props.indexOf(prop) == -1)
        props.push(prop);
    }
  });
  return props;
};

现在你可以创建一个过滤器函数来检查这个列表:

$scope.hasAllProperties = function(item){
  var found = true;
  angular.forEach($scope.properties(), function(prop){
    if(item[prop] == undefined){
      found = false;
      return;
    }
  });
  return found;
}
HTML:

<tr ng-repeat="country in countries | filter: hasAllProperties | orderBy: country.name">

您可能需要缓存属性的主列表,以减少$scope.properties()被调用的次数。

一种解决方案是使用filter过滤器:

<tr ng-repeat="country in countries | filter:{name: '', 1960: '', 1970: ''} | orderBy:'name'">

在你的控制器中创建一个过滤器,如下所示:

 $scope.search = function (item){
    return item.hasOwnProperty("1970");
  };

使用如下过滤器:

<tr ng-repeat="country in countries | filter:search | orderBy: country.name">

从您的URL派生一个新URL: http://cssdeck.com/labs/kggmrzow

试试这个:

<tr ng-repeat="country in countries | orderBy: country.name">
  <label ng-show="country.1960!=undefined && country.1970!=undefined">
    <td>{{country.name}}</td>
    <td>{{country.1960 | number}}</td>
    <td>{{country.1970 | number}}</td>
  </label>
</tr>