3

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>
robbymarston
  • 344
  • 3
  • 16
  • In your template, `logMonth(month);` is present and yet you don't have that argument in `$scope.logMonth`...what happens when you make that just `ng-change="logMonth()"`? – Zack Macomber Mar 08 '16 at 23:28
  • you get errors in console? – Sarantis Tofas Mar 08 '16 at 23:31
  • Just created a [jsFiddle](https://jsfiddle.net/snt8z7do/) and I'm unable to duplicate your issue. – Lex Mar 08 '16 at 23:35
  • the extra `});` in the code is it from copy paste ? – Sarantis Tofas Mar 08 '16 at 23:46
  • ZackMacomber and Akis_Tfs apologies, looks like I missed some stuff when I redacted some code to make it easier for you all to read, I just updated it. Lex thanks for testing, that'd likely indicate it's an issue with the surrounding code. – robbymarston Mar 14 '16 at 17:34

1 Answers1

0

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);">

whatoncewaslost
  • 2,216
  • 2
  • 17
  • 25
  • This did the trick. My text inputs and other form elements were using $rootScope and they behaved as expected so I assumed $scope would too. I'll have to do some more reading on the specifics because I'm relatively new to Angular.js. Thanks again! – robbymarston Mar 14 '16 at 18:06