根据外部ng-repeat中的值过滤内部ng-repeat

时间:2014-02-04 16:21:46

标签: angularjs

在下面的代码中,我想显示不同的标签,然后对于每个标签,我想过滤内部ng-repeat中的值。这可能吗?或者我是否必须创建一个单独的不同标签数组?

<!doctype html>
<html ng-app>
  <head>
    <script src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
    <script src="http://code.angularjs.org/1.2.9/angular-animate.min.js"></script>
  </head>
  <body>
    <div ng-init="servers = [
      {name:'UK001', os:'win 2008', tag:'prod'},
      {name:'UK002', os:'win 2008', tag:'prod'},
      {name:'UK003', os:'win 2003', tag:'Dev'},
      {name:'UK004', os:'win 2008', tag:'Dev'}
    ]">

        <div  ng-repeat="server in servers ">
            <h1> {{tag}}</h1>
           <ul >
                <li ng-repeat="server in servers | filter : {tag :server.tag } ">
                    <h3>{{server.name}} {{server.os}} </h3>
                </li>
              </ul>
        </div>   
    </div>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

这是一个吸虫:http://plnkr.co/edit/lhTmyp7BEtHGfJD2LFKr

您应该像这样创建标签对象:

var servers = [
    {name:'UK001', os:'win 2008', tag:'prod'},
    {name:'UK002', os:'win 2008', tag:'prod'},
    {name:'UK003', os:'win 2003', tag:'Dev'},
    {name:'UK004', os:'win 2008', tag:'Dev'}
];

$scope.tags = servers.reduce(function(tags,server){

  var tag = server.tag;

  if(! tags[tag] ) tags[tag] = [];

  delete server.tag; // we don't need it anymore

  tags[tag].push(server);

  return tags;
},{});

现在,您可以像这样迭代该对象:

<div ng-repeat="(tag, servers) in tags ">
  <h1> {{tag}}</h1>
    <li ng-repeat="server in servers">
        <h3>{{server.name}} {{server.os}} </h3>
    </li>      
</div>

tags对象的JSON表示:

{
  "prod": [
    {
      "name": "UK001",
      "os": "win 2008"
    },
    {
      "name": "UK002",
      "os": "win 2008"
    }
  ],
  "Dev": [
    {
      "name": "UK003",
      "os": "win 2003"
    },
    {
      "name": "UK004",
      "os": "win 2008"
    }
  ]
}