【问题标题】:Angular js filter for JSON key/value nested object is not working for meJSON键/值嵌套对象的Angular js过滤器对我不起作用
【发布时间】:2018-06-08 07:51:33
【问题描述】:

我的 JSON 数据类似于以下代码。谁能帮我按 state 属性中的 code/desc 过滤数据。

$scope.agent =
{
    "0d297c1711de":
    [{
        "applicationName": "rewards-accounts", "agentId": "0d297c1711de",
        "status": { "agentId": "0d297c1711de", "eventTimestamp": 1510580172247, "state": { "code": 100, "desc": "Running" } }
    }],
    "16f279d66923":
    [{
        "applicationName": "rewards-accounts-details", "agentId": "16f279d66923",
        "status": { "agentId": "0d297c1711de", "eventTimestamp": 1510580172247, "state": { "code": 201, "desc": "Unexpected Shutdown" } }
    }],
    "203b353d32ef":
    [{
        "applicationName": "rewards-accounts-details", "agentId": "203b353d32ef",
        "status": { "agentId": "0d297c1711de", "eventTimestamp": 1510580172247, "state": { "code": 200, "desc": "Shutdown" } }
    }]
};

我在 ng-repeat 中使用过这个过滤器。它不工作。 selectedCode 是我要过滤的模型数据。

| filter:{status:{ state: { code: **selectedCode**}}}

【问题讨论】:

  • 你的对象是被渲染但没有被过滤,还是它没有渲染并给你Error: [filter:notarray]

标签: angularjs json filter


【解决方案1】:

您可以使用自定义过滤器来过滤嵌套数据,

在你的控制器中创建你的过滤器

$scope.customFilter = function (row) {
    var result = false;
    if($scope.filter == undefined || $scope.filter == ""){
          result = true;
    }
    else{
         angular.forEach(row, function(value, key){
           if(value.state != undefined){
              if(value.state.code == $scope.filter)
                result = true;
           }
         });
    }
    return result;
};

并将此过滤器添加到您的 ng-repeat

<div ng-repeat="item in agent">
  <div ng-repeat="x in item | filter:customFilter">
    {{x}}
  </div>
</div>

Demo

【讨论】:

  • 它不工作。我没有使用控制器。我正在使用指令,我在指令中添加了自定义过滤器,但它不起作用。谢谢。
【解决方案2】:

this SO中所述

您需要传入参数以进行过滤,在您的特定情况下看起来像:

ng-repeat="a in agent | filter: {status: {state: {code: filter.key}}}"

感谢@Ray

JSFiddle here 供进一步参考。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    相关资源
    最近更新 更多