1

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.net/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?

7
  • use angular filter i think Commented Sep 6, 2013 at 9:34
  • might have to write your own, but it's not that hard Commented Sep 6, 2013 at 9:34
  • @kangoroo please elaborate, how I could use a filter to sort this? What would I filter? Commented Sep 6, 2013 at 9:38
  • well, actually you can probably use OrderBy as well 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... Commented Sep 6, 2013 at 9:44

1 Answer 1

5

Solution 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;
    };
});
Sign up to request clarification or add additional context in comments.

2 Comments

to make it a general solution, and much more re-usable - is there any way to make code a variable - so something like... (key, val) in someObject | getOrdered:"code"
Solution 2 does not work correctly. If you have code 2, 10, 15 they will be in the order 10,15,2 and not 2,10,15 even if you remove quotes from code values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.