Search code examples
angularjsselectng-optionsangularjs-ng-options

Angular multiple select not preselecting for non-empty ng-model


I have $scope.selectedUsers set as an array with just 1 object, which is an exact match of one of the objects from my available list of all $scope.users, altho the selected user is not highlighted in my <select multiple...>. Shouldn't it be highlighted?

Js:

$scope.selectedUsers = [ 
    { id: 2, name: "Jenny" }
];

$scope.users = [ 
  { id: 1, name: "Frank" },
  { id: 2, name: "Jenny" }     
];

Html:

<select multiple ng-model="selectedUsers" ng-options="user as user.name for user in users"></select>

Live demo: http://plnkr.co/edit/wpfvhvuShFVE07cyBE6M?p=preview

enter image description here


Solution

  • which is an exact match of one of the objects from my available list of all $scope.users

    No, they are not the same even though both objects has similar key-values. Angular uses strict comparison of objects (===) and two objects are equal only if they are the same object (references the same object).

    Correct code in your case:

    $scope.users = [ 
      { id: 1, name: "Frank" },
      { id: 2, name: "Jenny" }
    ];
    
    $scope.selectedUsers = [ 
      $scope.users[1]
    ];
    

    Demo: http://plnkr.co/edit/Czb7JuUzl7dPa08gsqUD?p=preview