简体   繁体   English

AngularJS:过滤json对象而不是数组

[英]AngularJS: Filtering json objects instead of an array

As filters provided by AngularJS only work with arrays but not with objects, i'm using the filter function suggested in this solution . 由于AngularJS提供的过滤器仅适用于数组而不适用于对象,因此我使用此解决方案中建议的过滤器功能。

Now i want to extend it, because my json data additionally has a settings-object storing the visibility data for the filtering (unfortunately i can not modify the json structure): 现在我想扩展它,因为我的json数据还有一个settings-object存储过滤的可见性数据(遗憾的是我无法修改json结构):

$scope.data = {
      "groups":{
        "1": {
          "type": "foo",
          "name": "blah", 
          "settings": {
            "visibility":[true]
          }
        },
        "2": {
          "type": "bar", 
          "settings": {
            "visibility":[false]
          }
        }
      }
}

Therefore also my filter call is more complex, but of course does not work with the filter at the moment: 因此我的过滤器调用也更复杂,但当然不适用于过滤器:

<div ng-repeat="(key, value) in data.groups | objectByKeyValFilter:'settings.visible[0]':true>
    {{key}} {{value.type}}
</div>

Probably 大概

objectByKeyValFilter:'settings.visibility[0]' : true

becomes wrongly something like that 变成了错误的东西

myObject['settings.visibility[0]']

How can i modify the filter function in order to achieve the filtering? 如何修改过滤功能以实现过滤?

Not working Plunker: http://plnkr.co/edit/f202lA?p=preview 不工作Plunker: http ://plnkr.co/edit/f202lA?p = preview

What about a bit different approach like this : plnkr 那个有点不同的方法怎么样: plnkr

 <div ng-repeat="(key, value) in data.groups ">
       <span ng-show="value.settings.visible">
        {{key}} {{value.type}}
        <span>


      </div> 

Ok let's have a looke here http://plnkr.co/edit/MgltNXw0x2KWcmWm6QeA?p=preview 好的,我们这里有一个looke http://plnkr.co/edit/MgltNXw0x2KWcmWm6QeA?p=preview

<div ng-controller ="test">
      <div ng-repeat="(key, value) in data.groups | objectByKeyValFilter:'settings.visible':'true'">
        {{key}} {{value.type}}
      </div> 
    </div> 

true or false has to be inside quote marks true或false必须在引号内

JS: JS:

angular.module('app').filter('objectByKeyValFilter', function() {
  return function(input, filterKey, filterVal) {


    var filteredInput = [];
    angular.forEach(input, function(value, key) {

      if (value.settings.visible == filterVal) {


        filteredInput.push(value);
      }

    });

    return filteredInput;
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM