5

I'm trying to preselect options on my multiselect. In order to make my case clear, I've made a JSFiddle.

<select ng-model="properties" id="props" multiple 
ng-options="option.name group by option.category for option in options"></select>

Unfortunately, I am bound by the way the object is received, so I guess I need the ng-options attribute.

Does anybody have an idea how I can get both 'Captain America' and 'Dr. Doom' selected on load?

2 Answers 2

3

Try changing your controller code to:

   function TestCtrl($scope) {

    var myOptions = [{
        "id": "4",
        "name": "Captain America",
        "categoryId": "1",
        "category": "Heroes"
    }, {
        "id": "5",
        "name": "Iron Man",
        "categoryId": "1",
        "category": "Heroes"
    }, {
        "id": "10",
        "name": "Magneto",
        "categoryId": "2",
        "category": "Vilains"
    }, {
        "id": "9",
        "name": "Dr. Doom",
        "categoryId": "2",
        "category": "Vilains"
    }];

    $scope.options = myOptions;


    $scope.properties = [myOptions[0], myOptions[3]];
}

Explanation: you are setting your selected options (properties) to different instances of the objects than the ones that compose the full list. Use the same object references as shown above.

Sign up to request clarification or add additional context in comments.

Comments

2

You are super close, two changes. Define the attributes in your controller like this

$scope.properties = ["Captain America", "Dr. Doom"];

And add a small piece to your ng-options like this

ng-options="option.name as option.name group by option.category for option in options"

Your option.name as will determine what the saved feature looks like in $scope.properties

1 Comment

You could also do $scope.properties=["4","9"] and use option.id as option.name

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.