icanc
icanc

Reputation: 3577

How do you change the selected value of a select input from the controller?

My template:

<select ng-model="state" ng-options="state.name for state in states">
    <option value="">ALL</option>
</select>

My controller:

var stateList = [
  { name: 'ALABAMA', abbreviation: 'AL'},
  { name: 'ALASKA', abbreviation: 'AK'},
  { name: 'ARIZONA', abbreviation: 'AZ'},
  { name: 'ARKANSAS', abbreviation: 'AR'},
  ...
]

$scope.states = stateList;
$scope.state = 'ALL';  // Default

$scope.updateStateModel = function(state) {
  $scope.state = state.toUpperCase();  // Does nothing
};

The value of $scope.state does change but is not reflected on the <select> input. How do you properly bind it so that the value of <select> is in sync with $scope.state ?

Upvotes: 0

Views: 199

Answers (1)

Alex Choroshin
Alex Choroshin

Reputation: 6187

The ngModel needs to be bound to the same object type, here's a working example:

html:

<div ng-app="App"  ng-controller="ctrl">
<select ng-model="state" ng-options="state.name for state in states">
    <option value="">ALL</option>
</select>
    <div ng-repeat="state in states"><span ng-click="updateStateModel(state)">{{state.name}}</span></div>
</div>

js:

function ctrl($scope) {
        $scope.states = [{name:"aa"},{name:"bb"},{name:"cc"}];
    $scope.state = 'ALL';  // Default

    $scope.updateStateModel = function(state) {
      $scope.state = state; 
    };
 }

Live example: http://jsfiddle.net/choroshin/3RGpv/

Upvotes: 1

Related Questions