gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:52:20 26 4
gpt4 key购买 nike

我有一个对象存储在 Controller 内的 $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>

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

Plunker

关于javascript - ng-repeat 中按键自定义对象排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47791283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com