AngularJS显示分层数据

时间:2015-07-22 03:33:05

标签: angularjs filtering

我试图在分层视图中显示数据列表。 我的数据看起来像这样:

OAEPWithSHA-512AndMGF1Padding

我的控制器如下:

BigInteger modBigInteger = new BigInteger(1, modulus);//modulus must be byte array
BigInteger exBigInteger = new BigInteger(1, exponent);//exp must be byte array

RSAPublicKeySpec spec = new RSAPublicKeySpec(modBigInteger, exBigInteger);
KeyFactory factory = KeyFactory.getInstance("RSA");
PublicKey publicKey = factory.generatePublic(spec);

我的HTML看起来像:

items:[
  {
    "model_id": "1",
    "model_type_id": "1",
    "name": "Parent 1",
    "model_parent_id": ""
  },
  {
    "model_id": "2",
    "model_type_id": "1",
    "name": "Parent 2",
    "model_parent_id": ""
  },
  {
    "model_id": "3",
    "model_type_id": "2",
    "name": "Child 1",
    "model_parent_id": "1"
  },
  {
    "model_id": "4",
    "model_type_id": "2",
    "name": "Child 2",
    "model_parent_id": "2"
  }
]

过滤器在我尝试使用外部控制器过滤内部控制器时无法正常工作。我让两个孩子都显示在每个家长的下方。如何显示父级,并且只显示子级,其中childs model_parent_id等于父级的model_id?

1 个答案:

答案 0 :(得分:1)

虽然我不确定是否有办法使用过滤器实现此目的,但显示嵌套数据的常规方法是重新组织数据结构以反映您想要显示的内容。

items:[
  {
    "model_id": "1",
    "model_type_id": "1",
    "name": "Parent 1",
    "children": [{
      "model_id": "3",
      "model_type_id": "2",
      "name": "Child 1"
    }]
  },
  {
    "model_id": "2",
    "model_type_id": "1",
    "name": "Parent 2",
    "children": [{
      "model_id": "3",
      "model_type_id": "2",
      "name": "Child 2"
    }]
  }
]

然后使用嵌套的ng-repeat

显示它们
<ul>
  <li ng-repeat="parent in items">
    {{parent.name}} - {{parent.model_id}}
    <ul>
      <li ng-repeat="child in parent.children">
        {{child.name}} - {{child.model_id}}
      </li>
    </ul>
  </li>
</ul>

注意:不需要使用嵌套控制器,只需在顶层使用一个控制器即可。如果需要递归使用某些共享逻辑,请使用自定义指令替换li。

要重新组织数据,您可以在服务器端或客户端执行此操作。 以下显示了如何在客户端进行操作,因为我们可能没有更改服务器端API的权限。

$scope.data = [];
angular.forEach(items, function(item) {
    if (item.model_parent_id == "") {
        $scope.data.push(item);
    }  
});

// add all parents first in case some children comes before parent
angular.forEach(items, function(item) {
    if (item.model_parent_id == "") continue;

    // search for parent
    angular.forEach($scope.data, function(parent) {
        if (parent.model_id == item.model_parent_id) {
            if (!parent.children) parent.children = [];
            parent.children.push(item);
        }
    }
});
相关问题