【问题标题】:Angular bind to filtered count角度绑定到过滤计数
【发布时间】:2016-06-29 08:08:54
【问题描述】:

我有这个数组:

[
    {
      type: "hhh",
      items: [
        {
          "name": "EGFR",
          "type": "a",
          "selected": true
        }
      ]
    },
    {
      type: "aaa",
      items: [
        {
          "name": "mm",
          "type": "b",
          "selected": false
        }
      ]
    },
    {
      type: "ii",
      items: [
        {
          "name": "pp",
          "type": "bb",
          "selected": true
        }
      ]
    }
  ]

我想显示具有选定属性“true”的项目的计数器。 我希望它在更改时实时更改。 (不带手表和功能)

谢谢!

【问题讨论】:

  • 如何更改数组?通过任何后端调用/Ajaz/API 等?

标签: javascript angularjs lodash


【解决方案1】:

方法如下:

var current_selected = {
get amount(){
    var res = 0;
    arr.forEach(function(item, i, arr) {
      if (item.items[0].selected) res++;
      })
      return res;
  }
}

调用:

current_selected.amount

Fiddle

【讨论】:

    【解决方案2】:

    您可以使用 JsonPath 来获取计数。使用 JsonPath 还具有处理复杂 json 结构的额外优势。对于您提供的示例,您只需要包含 jsonpath js 文件并在脚本中使用以下内容:

    console.log(arr);
    var filtered = jsonPath(arr, "$.[*].items[?(@.selected==true)]");
    console.log(filtered);
    console.log(filtered.length);
    

    其中 arr 是您的 json 结构。

    JsonPath 可以从: https://code.google.com/archive/p/jsonpath/downloads

    JsonPath 帮助: http://goessner.net/articles/JsonPath/

    其他来源可能有更新版本,但那是我研究过的版本

    【讨论】:

      猜你喜欢
      • 2018-06-09
      • 2015-08-02
      • 1970-01-01
      • 2021-03-25
      • 2018-10-01
      • 1970-01-01
      • 2015-12-15
      • 2015-05-25
      相关资源
      最近更新 更多