I just asked about generating a select from key/value map instead of array: AngularJS select box generated from object
That is all working fine now: /
<select ng-model="current.addressCode" ng-options="value.code as value.name for (key, value) in student.address | orderBy: 'code'"</select>
... and js ...
$scope.student = {
address: {
select: {
code: "0",
name: "Select proof of address"
},
letter: {
code: "1",
name: "Letter"
},
photograph: {
code: "3",
name: "Photograph"
}
},
But the only thing missing, is how to order the select items.
How can I order select items in a select box generated from key/value map in angularjs?
I just asked about generating a select from key/value map instead of array: AngularJS select box generated from object
That is all working fine now: http://jsfiddle/UPWKe/1/
<select ng-model="current.addressCode" ng-options="value.code as value.name for (key, value) in student.address | orderBy: 'code'"</select>
... and js ...
$scope.student = {
address: {
select: {
code: "0",
name: "Select proof of address"
},
letter: {
code: "1",
name: "Letter"
},
photograph: {
code: "3",
name: "Photograph"
}
},
But the only thing missing, is how to order the select items.
How can I order select items in a select box generated from key/value map in angularjs?
Share Improve this question edited May 23, 2017 at 12:11 CommunityBot 11 silver badge asked Sep 6, 2013 at 9:20 Billy MoonBilly Moon 58.7k27 gold badges148 silver badges244 bronze badges 7- use angular filter i think – kangoroo Commented Sep 6, 2013 at 9:34
- might have to write your own, but it's not that hard – kangoroo Commented Sep 6, 2013 at 9:34
- @kangoroo please elaborate, how I could use a filter to sort this? What would I filter? – Billy Moon Commented Sep 6, 2013 at 9:38
- well, actually you can probably use OrderBy as well – kangoroo Commented Sep 6, 2013 at 9:41
- @kangoroo I did try using orderBy, but I could not figure out how to get it to work. I would be grateful of any suggestions... – Billy Moon Commented Sep 6, 2013 at 9:44
1 Answer
Reset to default 5Solution 1: You can use another array to store the order of the fields. For this you would need to use ng-repeat
in place of ng-options
:
$scope.studentAddressFields = [
"select",
"letter",
"photograph"
]
HTML:
<select ng-model="current.addressCode">
<option ng-repeat="field in studentAddressFields"
value="student.address[field]['code']">
{{student.address[field]['name']}}
</option>
</select>
Solution 2: Using a filter:
HTML:
<select ng-model="current.addressCode" ng-options="code as details.name
for (code, details) in student.address | getOrdered">
</select>
Filter:
myApp.filter('getOrdered', function() {
return function(input) {
var ordered = {};
for (var key in input){
ordered[input[key]["code"]] = input[key];
}
return ordered;
};
});