使用AngularJS

时间:2016-07-03 04:19:30

标签: arrays angularjs sorting

如果我有一个包含对象数组的数据集,每个对象都有一个数组,那么我如何按其属性对子数组进行排序?例如,这里是一些示例音乐数据,它有2张专辑,其中包含曲目:

albums: [
  {
    type: "album",
    name: "Brothers",
    tracks: [
      {
        type: "track",
        name: "Everlasting Light"
      },
      {
        type: "track",
        name: "Next Girl"
      },
      {
        type: "track",
        name: "Tighten Up"
      }
    ]   
  },
  {
    type: "album",
    name: "Listen",
    tracks: [
      {
        type: "track",
        name: "Around Town"
      },
      {
        type: "track",
        name: "Forgive & Forget"
      }
    ]   
  }
]

结果如下:

- Around Town
- Everlasting Light
- Forgive & Forget
- Next Girl
- Tighten Up

有什么方法可以使用ng-repeat创建按字母顺序排序的音乐曲目列表

我想象它的工作方式如下,但我没有成功。

<p ng-repeat="track in albums.tracks">{{track.name}}</p>

2 个答案:

答案 0 :(得分:1)

由于您只需要专辑的曲目,您应该将所有曲目合并到一个数组中,然后按字母顺序对其进行排序。这是一个片段:

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

app.controller('mainCtrl', function($scope) {
  $scope.albums = [
    {  
      "type":"album",
      "name":"Brothers",
      "tracks":[  
         {  
            "type":"track",
            "name":"Everlasting Light"
         },
         {  
            "type":"track",
            "name":"Next Girl"
         },
         {  
            "type":"track",
            "name":"Tighten Up"
         }
      ]
   },
   {  
      "type":"album",
      "name":"Listen",
      "tracks":[  
         {  
            "type":"track",
            "name":"Around Town"
         },
         {  
            "type":"track",
            "name":"Forgive & Forget"
         }
      ]
   }
];
  
  $scope.tracks = [];
  angular.forEach($scope.albums, function(value) {
    $scope.tracks = $scope.tracks.concat(value.tracks);
  });
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js">
</script>
</head>

<body ng-controller="mainCtrl">
  <div ng-repeat="track in tracks | orderBy:'name'">
    <span ng-bind="track.name"></span>
  </div>
</body>
</html>

答案 1 :(得分:0)

您可以使用orderby过滤器根据属性对列表进行排序。有角度的网站有关于此https://docs.angularjs.org/api/ng/filter/orderBy

的更多信息

这是一个可能有帮助的傻瓜,https://plnkr.co/edit/goxNA9PvBeFL0hyWp9hR?p=preview

您可以直接在html中使用过滤器按属性排序。

<div ng-repeat="album in albums">
    <h2>{{album.name}}</h2>
      <div ng-repeat="track in album.tracks | orderBy:'name'">
          {{track.name}}
      </div>
</div>