Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Preselecting Options on Multiple Select

Tags:

angularjs

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?

like image 808
user3038187 Avatar asked Nov 26 '13 20:11

user3038187


People also ask

How do I select multiple options in select?

Selecting multiple options vary in different operating systems and browsers: For windows: Hold down the control (ctrl) button to select multiple options. For Mac: Hold down the command button to select multiple options.

What form controls we use when we want the user to choose multiple options from a list?

Use a list box when you want to: Enable users to make multiple choices from a set of predefined options.

How do you select multiple options in Javascript?

To select multiple options in a drop-down list, use the multiple properties. It allows you to select more than one option while pressing CTRL key.

Which of the following attribute is used to allow multiple selections in a dropdown menu?

Adding the multiple attribute to <select> allows the user to select more than one option. The user will need to hold down the ctrl or cmd key to select more than one option in the list, so you will need to add some explanatory text.


1 Answers

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.

like image 145
Phil Sandler Avatar answered Sep 27 '22 22:09

Phil Sandler