在 ng-repeat 中按键自定义对象排序

Custom sorting of objects by key in ng-repeat

我有一个对象存储在控制器内的 $scope.addresscards 中。 js如下:

var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
  $scope.addresscards = {
      "work_address": {
          "location":"workLoc",
          "address": "workAddr",
          "flat_no": "worknumber",
          "landmark": "workLandmark"
      },
      "random1_address": {
          "location":"someLoc",
          "address": "SomeAddr",
          "flat_no": "Somenumber",
          "landmark": "someLandmark"
      },
      "home_address": {
          "location":"homeLoc",
          "address": "homeAddr",
          "flat_no": "homenumber",
          "landmark": "homeLandmark"
      },
      "random2_address": {
          "location":"someLoc2",
          "address": "SomeAddr2",
          "flat_no": "Somenumber2",
          "landmark": "someLandmark2"
      }
  };
}

我正在使用 ng-repeat 来显示地址。这是 HTML:

<div ng-controller="MyCtrl">
  <ul ng-repeat="(addressKey,addressVal) in addresscards">
     <li>{{addressKey}} has :: {{addressVal.location}},{{addressVal.address}}, {{addressVal.location}}, {{addressVal.address}}</li>
  </ul>
</div>

我的输出是:

home_address has :: homeLoc, homeAddr, homeLoc, homeAddr
random1_address has :: someLoc, SomeAddr, someLoc, SomeAddr
random2_address has :: someLoc2, SomeAddr2, someLoc2, SomeAddr2
work_address has :: workLoc, workAddr, workLoc, workAddr

我想显示输出,如果对象有 home_address,它应该显示在第一位,如果对象有 work_address,它应该显示在第一位。然后对象的其余部分应按字母顺序显示。

这是我想要显示的预期结果:

home_address has :: homeLoc, homeAddr, homeLoc, homeAddr
work_address has :: workLoc, workAddr, workLoc, workAddr
random1_address has :: someLoc, SomeAddr, someLoc, SomeAddr
random2_address has :: someLoc2, SomeAddr2, someLoc2, SomeAddr2

我用 orderBy 试过了,它对对象不起作用。我该如何实现?

您可以向您的地址对象添加 属性

$scope.addresscards = {
      "work_address": {
          "location":"workLoc",
          "address": "workAddr",
          "flat_no": "worknumber",
          "landmark": "workLandmark",
          "sort" : "2"
      },
      "random1_address": {
          "location":"someLoc",
          "address": "SomeAddr",
          "flat_no": "Somenumber",
          "landmark": "someLandmark"
      },
      "home_address": {
          "location":"homeLoc",
          "address": "homeAddr",
          "flat_no": "homenumber",
          "landmark": "homeLandmark",
          "sort" : "1"
      },
      "random2_address": {
          "location":"someLoc2",
          "address": "SomeAddr2",
          "flat_no": "Somenumber2",
          "landmark": "someLandmark2"
      }
  };

并且在您的 ng-repeat 中,您可以先通过排序对多个字段进行排序以首先显示家庭和工作地址,然后通过地址键按字母顺序排列。

  <ul ng-repeat="(addressKey,addressVal) in addresscards | orderBy:['sort','addressKey']">
     <li>{{addressKey}} has :: {{addressVal.location}},{{addressVal.address}}, {{addressVal.location}}, {{addressVal.address}}</li>
  </ul>

或者在您的控制器中,您可以对所有其他地址进行排序,并将家庭和工作地址附加到列表的开头。

Plunker