AngularJS OrderBy对象内部数组的第一个元素的数组值

时间:2018-05-31 02:45:07

标签: angularjs

我有一个如下所示的数组:

$scope.items = {
  books: [
   {position: 1},
   {title: 'Harry Potter'},
   {title: 'Lord of The Rings'}
  ],
  movies: [
   {position: 0},
   {title: 'Mission Impossible'},
   {title: 'Star Wars'}
  ]
};

我想按数组项的第一个元素排序,这是我尝试过的:

<div class="item" ng-repeat="item in items | orderBy:items[0].position">
  {{item}}
</div>

但是这给出了语法错误。

4 个答案:

答案 0 :(得分:3)

您无法将orderBy应用于对象,因此您需要创建中间$scope.itemsArray并改为使用它:

angular.module('app', []).controller('ctrl', function($scope){
  $scope.items = {
    books: [
     {position: 1},
     {title: 'Harry Potter'},
     {title: 'Lord of The Rings'}
    ],
    movies: [
     {position: 0},
     {title: 'Mission Impossible'},
     {title: 'Star Wars'}
    ]
  };
  $scope.itemsArray = [];
  for(var prop in $scope.items){
    var val =  $scope.items[prop];
    $scope.itemsArray.push({key: prop, val, sort: val[0].position})
  }    
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>

<ul ng-app='app' ng-controller='ctrl'>
  <li ng-repeat='item in itemsArray | orderBy : "sort"'>{{item.key}} : {{item.val}}</li>
</ul>

答案 1 :(得分:1)

项目是json对象的键和值。所以orderBy:items [0] .position没有意义,因为没有项目[0]。

当我们执行item in items时,它将遍历项目的每个键,因此这应该有效

orderBy : items[item][0].position

答案 2 :(得分:1)

您应该重新映射数据,以实现所需的输出

模型应该是这样的

[{
  name: string,
  position: number,
  titles: string[]
}]

为此实现这样做

$scope.items = {
    books: [
        { position: 1 },
        { title: 'Harry Potter' },
        { title: 'Lord of The Rings' }
    ],
    movies: [
        { position: 0 },
        { title: 'Mission Impossible' },
        { title: 'Star Wars' }
    ]
};
$scope.final = [];
_init();
function _init() {       
    $scope.final = [];
    //Iterate the keys
    for (var x in $scope.items) {
        var data = {
            name: x,//store the key in the name
            position: $scope.items[x][0].position,//position
            titles: []
        }
        //iterate every item 
        for (var y of $scope.items[x]) {
            //push only the title items
            if (y.hasOwnProperty("title")) {
                data.titles.push(y.title);
            }
        }
        $scope.final.push(data);
    }
    console.log($scope.final)
}

在视图中应该是这样的

<div class="item" ng-repeat="item in final | orderBy:'position'">
  {{item.name}}
  <ul>
    <li ng-repeat="title in item.titles">
      {{title}}
    </li>
  </ul>
</div>

答案 3 :(得分:0)

只需使用字段名称

即可
<div class="item" ng-repeat="item in items | orderBy:'position'">

你也有对象内的数组,所以你需要迭代数组,

div class="item" ng-repeat="item in items.books | orderBy:'position'">