使用AngularJS对对象进行分组 [英] Grouping objects with AngularJS

查看:91
本文介绍了使用AngularJS对对象进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数组中有一堆对象,我试图弄清楚如何在Angular中继器中对它们进行分组.例如,我想使用parentTag键将水果项分组到父项的Tag键.因此,Fruit的标签为1,Apple的父标签为1,这意味着Apple与Fruit分组.

I have a bunch of objects in an array and I am trying to figure out how to group them within an Angular repeater. For example I want to group the fruit items with a parentTag key to the Tag key of a parent. So Fruit has a tag of 1 and Apple has a parent tag with a value of 1, meaning Apple is grouped with Fruit.

因此使用此数组...

so using this array...

[
{
    "code":"Fruit",
    "tag":1
},
{
    "code":"Apple",
    "tag":2,
    "parentTag":1
},
{
    "code":"Vegetable",
    "tag":3
},
{
    "code":"Meat",
    "tag":4
},
{
    "code":"Banana",
    "tag":5,
    "parentTag":1
},
{
    "code":"Carrot",
    "tag":6,
    "parentTag":3
},
{
    "code":"Chicken",
    "tag":7,
    "parentTag":4
}
]

我正在尝试将对象分组为此类...

I am trying to group the objects like this...

水果

  • 苹果
  • 香蕉

蔬菜

  • 胡萝卜

  • 鸡肉

到目前为止,我有一个仅显示对象的中继器...

So far I have a repeater that only displays the objects...

<div ng-repeat="product in products">
{{code}}
<span ng-if="product.tag != null">{{product.tag}}</span>
<span ng-if="product.parentTag > null">{{product.parentTag}}</span>
</div>

但是在这种情况下,我不知道如何使用groupBy.有什么想法吗?

But I don't know how to use the groupBy in this case. any ideas?

推荐答案

请参阅下面的演示

var app = angular.module('app', []);

app.controller('homeCtrl', function($scope) {

  $scope.products = [{
    "code": "Fruit",
    "tag": 1
  }, {
    "code": "Apple",
    "tag": 2,
    "parentTag": 1
  }, {
    "code": "Vegetable",
    "tag": 3
  }, {
    "code": "Meat",
    "tag": 4
  }, {
    "code": "Banana",
    "tag": 5,
    "parentTag": 1
  }, {
    "code": "Carrot",
    "tag": 6,
    "parentTag": 3
  }, {
    "code": "Chicken",
    "tag": 7,
    "parentTag": 4
  }];


});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body>
  <div ng-app="app">
    <div ng-controller="homeCtrl">
      <div ng-repeat="product in products | filter :{parentTag:'!'}">
        <h3>{{product.code}}</h3>
        <div ng-repeat="subproduct in products | filter :{parentTag:product.tag}">
          <span>{{subproduct.code}}</span>
          <span>{{subproduct.tag}}</span>
          <span>{{subproduct.parentTag}}</span>
        </div>


      </div>
    </div>
</body>

这篇关于使用AngularJS对对象进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆