robbymarston
robbymarston

Reputation: 356

Model isn't updating when selected option changes

My Angular.js project features a select element bound to a model. On load the appropriate option is selected however selecting another option doesn't seem to update the model, at least not permanently. If I change the model programmatically however the results are as expected.

The controller:

angular.module('myApp.controllers').controller('HomeCtrl',function($scope){
  $scope.month = "08"; // this default value is selected on-load as expected
  $scope.updateMonth = function() {
   console.log($scope.month); // this shows the original value not the newly selected value
   // a http request and other things happen here...
  };
  $scope.logMonth = function(month) {
   console.log(month); // this shows the newly selected value as expected
  }
 });

The template:

<select ng-model="month" ng-change="logMonth(month);">
 <option value="07">07</option>
 <option value="08">08</option>
 <option value="09">09</option>
</select>
<button ng-click="updateMonth();">Update Month</button>

Upvotes: 3

Views: 400

Answers (1)

whatoncewaslost
whatoncewaslost

Reputation: 2256

Sounds like an angular scoping problem. Scope inheritance applies to objects on scopes but not to primitives. Try changing $scope.month = "08" to $scope.month = {selected: "08"}. Then in your controller, change the html to the following.

<select ng-model="month.selected" ng-change="logMonth(month.selected);">

Upvotes: 0

Related Questions