我有一个对象存储在控制器内的$ 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,它应该显示在1st,然后如果对象有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尝试了它,它不适用于对象。我如何实现这一目标?
答案 0 :(得分:1)
您可以向地址对象添加属性
$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>
或者在您的控制器中,您可以对所有其他地址进行排序,并将家庭和工作地址附加到列表的开头。