【问题标题】:NgRepeat filtering complex structureNgRepeat过滤复杂结构
【发布时间】:2014-03-21 02:36:01
【问题描述】:

我得到了一个复杂的 JSON 对象来显示在 Angular 中,我想在深入研究对象后将它过滤到两个列表中。

对象结构为:

{
  foo:
  {
    bar:
    {
      showA: { value: true, type: 'A' },
      showB: { value: false, type: 'A' },
      showC: { value: true, type: 'A' }
    }
  }
}

我正在尝试实现“假”和“真”的列表。

在这种情况下:

已禁用:

  • showB - 类型:A

启用:

  • showA - 类型:A
  • showC - 类型:A

我无法过滤对象,也无法获取对象的“键”,例如“showA”。

我的使用尝试:

item in profile['foo']['bar'] | filter: { value: false }

访问正确的对象,但我无法过滤或获取它的“键”。

这里有一个坏掉的 plunkr 来演示:

http://plnkr.co/edit/9NniQdo213AuEbf0pghA?p=preview

任何建议都会很棒!

【问题讨论】:

    标签: angularjs angularjs-ng-repeat


    【解决方案1】:

    看看这个工作的朋克:http://plnkr.co/edit/TdM9P592OXd6Bx81Bmbt?p=preview

    它使用自定义过滤器myFilter,这使得过滤任务非常简单。 myFilter 返回一个新对象,其中只有对象的值等于作为过滤器的第二个参数给出的值。

    app.filter('myFilter', function() {
      return function(bar, value) {
        var r = {};
        for (var key in bar) {
          if (bar[key].value == value) {
            r[key] = bar[key];
          }
        }
        return r;
      }
    });
    

    要使用ng-repeat 获取密钥,请使用以下语法:

        <li ng-repeat="(key, item) in profile['foo']['bar'] | myFilter:false">
          <input type="checkbox" ng-model="item.value" /> {{ key }}
        </li>
    

    如果你可以改变$scope.profile的结构,使用这个结构过滤任务会更容易:

    bar: [
        {name: 'ShowA', value: false, type: 'A'},
        ...
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-28
      • 1970-01-01
      • 1970-01-01
      • 2018-10-20
      相关资源
      最近更新 更多