AngularJS: Select does not change the selected option when changing a variable related scope

I have a control. Its parameters are generated dynamically from an array of objects. In the init application, I want to select a specific option by changing the associated variable in the scope.

This does not work when the ng-option returns a full object. However, it works when select ng-option returns a string.

Is this an angular error or am I something wrong?

HTML:

<div ng-controller="selectCtrl" ng-app> Doesn't work when select ngModel value is object:<br /> <select ng-model="valueObject" ng-options="o.label for o in options"></select><br /> <pre>{{valueObject | json}}</pre> Works when select ngModel value is string:<br /> <select ng-model="valueString" ng-options="o.value as o.label for o in options"></select> <pre>{{valueString | json}}</pre> 

JS:

 function selectCtrl($scope) { $scope.options = [ {label: 'a', value: '1', someId: 333}, {label: 'b', value: '2', someId: 555} ]; $scope.valueObject = {label: 'a', value: '1', someId: 333}; $scope.valueString = '1'; }; 

JS Fiddle: http://jsfiddle.net/apuchkov/FvsKW/6/

+7
javascript angularjs
source share
3 answers

The expression should be used to set an example in my work with questions. More details here: http://leoshmu.wordpress.com/2013/09/11/making-the-most-of-ng-select/

Updated JsFiddle: http://jsfiddle.net/apuchkov/FvsKW/9/

HTML

 <div ng-controller="selectCtrl" ng-app> Doesn't work when select ngModel value is object:<br /> <select ng-model="valueObject" ng-options="o.label for o in options"></select><br /> <pre>{{valueObject | json}}</pre> Does work when select ngModel value is object AND 'track by' expression is used:<br /> <select ng-model="valueObject" ng-options="o.label for o in options track by o.value"></select><br /> <pre>{{valueObject | json}}</pre> </div> 

Js

 function selectCtrl($scope) { $scope.options = [ {label: 'a', value: '1', someId: 333}, {label: 'b', value: '2', someId: 555} ]; $scope.valueObject = {label: 'a', value: '1', someId: 333}; }; 
+9
source share

The key is that objects with the same keys and values ​​are not equal to each other ( ref ES 5.1 Specification 11.9.6 ):

 // Return true if x and y refer to the same [in-memory] object. // Otherwise, return false. > var one = {label: 'a', value: '1', someId: 333} > var two = {label: 'a', value: '1', someId: 333} > one === one true > two === two true > one === two false > one == two false 

Change $scope.valueObject = { /* similar object */ } to $scope.valueObject = $scope.options[0] and everything should work.

+5
source share

It should work for such a controller:

 function selectCtrl($scope) { $scope.options = [ {label: 'a', value: '1', someId: 333}, {label: 'b', value: '2', someId: 555} ]; $scope.valueObject = $scope.options[ 0 ]; }; 
0
source share

All Articles