简体   繁体   English

如何在AngularJS中按键值过滤json列表?

[英]How do you filter a json list by key-value in AngularJS?

I'm quite a beginner to AngularJS. 我是AngularJS的初学者。 Now I'm trying to list out a json file using ng-repeat . 现在我想用ng-repeat列出一个json文件。 These are what I have: 这些就是我所拥有的:

filename.json: filename.json:

{
  "name"    : "name data",
  "id"      : "id data",
  "country" : "country data",
  "age"     : "age data",
  "job"     : "job data"
}

The list is much longer than this one, but I could print everything into a table successfully by ng-repeat but without any filter. 该列表比这个列表长得多,但我可以通过ng-repeat成功地将所有内容打印到表中但没有任何过滤器。 Now, I'm trying to take some items out. 现在,我正试着拿出一些东西。 In the example, I might want to show without "id" and "age". 在示例中,我可能希望显示没有“id”和“age”。 Is there any suggestion to make a filter for this situation? 有没有建议过滤这种情况?

The following is what I've tried after looking up on several answers on Stack Overflow but failed. 以下是我在查看Stack Overflow上的几个答案后尝试过的但是失败了。 The answers are great but their situations don't really fit mine. 答案很棒,但他们的情况并不适合我的。

template: 模板:

<table>
  <tr ng-repeat="(key, data) in $ctrl.person | filter: $ctrl.toShow">
    <td>{{key}}</td>
    <td>{{data}}</td>
  </tr>
</table>

controller function: 控制器功能:

function myCtrl ($http) {
  self = this; 
  self.toShow = function myFilter (key, value) {
    if (key == 'id' || key == 'age') {
      return false;
    } else {
      return true;
    }
  };
  $http.get('filename.json').then(function (response) {
    self.person = response.data;
  });
}
 app.filter('toShow', function () {
     return function (input) {
         return JSON.parse(input, ['field1', 'field2']);
     });
 });

The code above is based on fact that JSON.parse() can have second argument being an array of JSON field to grab. 上面的代码基于以下事实: JSON.parse()可以将第二个参数作为要抓取的JSON字段数组。 Here you put fields to show rather than to hide. 在这里你要显示字段而不是隐藏。

You can use ng-repeat with ng-show to filter fields you want to hide as below 您可以使用ng-repeat和ng-show过滤要隐藏的字段,如下所示

<table>
    <tr ng-repeat="(key, data) in $ctrl.person" ng-show="key != 'id' && key != 'age'">
        <td>{{key}}</td>
        <td>{{data}}</td>
    </tr>
</table>

Working fiddle 工作小提琴

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

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