Update:
If you want to go directly to the link used in this answer, here is this:
Link: Initial selection in AngularJS ng-options with track
Here is what worked for me:
app.controller('fooController', function($scope){ $scope.roles = [{id:1, name:"Administrator"}, {id:2, name: "Student"}]; $scope.user = {}; $scope.user.roles = [ $scope.roles[0] ]; });
An error occurred in the plunger: user not initialized, except that Angular would compare every object in the ng-options array with all elements of the ng-model array. JavaScript comparison is not Angular comparison; comparing two objects with the same properties in JavaScript returns false (different objects).
Plunk: http://plnkr.co/edit/ccsAVvPACnN6Qzje7HcB?p=preview
.
Now this is not perfect. Usually you want to adjust them based on ID or so, otherwise:
In HTML, use track by to tell AngularJS to compare identifiers instead of whole objects:
<select multiple class="form-control" data-ng-model="user.roles" data-ng-options="role.name for role in roles track by role.id" required=""></select>
Then in your controller you can use any object without actually being in the array:
app.controller('fooController', function($scope){ $scope.roles = [{id:1, name:"Administrator"}, {id:2, name: "Student"}]; $scope.user = {}; $scope.user.roles = [ {id:1, name:"Administrator"} ]; });
Plunk: http://plnkr.co/edit/NKLXrwqwk36YfhBSXILN?p=preview
Note that I didn’t even need the name property. It’s easy to create a suitable object later, but it really doesn’t need to be matched now, try without it!
.
I wrote a detailed tutorial with an accompanying video about this choice problem and its options. He focused on a single, but multi-select just uses an array of objects, not a single object directly.
Check this out for a better understanding - highly recommended:
Initial selection in AngularJS ng-options with track
.
Let me know in the comments if you are still struggling with this.