AngularJS Select the OnChange result not reflected in the attached template

advertisements

I have the following markup inside my directive:

<select class="form-control"
ng-change="changeLanguage()"
ng-model="selectedLanguage"
ng-options='lang.key as lang.name for lang in languages'></select>
<p>{{selectedLanguage}}</p>

And my directive's controllers relevant part is this:

$scope.languages = [{
    name: "Java",
    key: "java",
}, {
    name: "C",
    key: "c",
}];

$scope.$watch("selectedLanguage", function(newValue, oldValue) {
    console.log("watch", newValue, oldValue);
});

$scope.changeLanguage = function() {
    console.log("language changed: " + $scope.selectedLanguage)
}

However, when I change it via UI, it is not reflected in the controller, but it is available in the UI, I see the selected value. I tried both $watch and onChange to see, but both of them don't work. What is wrong here?


Seems to work fine for me. Here is an example of it working with the code you provided.

var app = angular.module('myApp', []);

app.controller('Ctrl', function($scope) {

  $scope.languages = [{
    name: "Java",
    key: "java",
  }, {
    name: "C",
    key: "c",
  }];

  $scope.$watch("selectedLanguage", function(newValue, oldValue) {
    console.log("watch", newValue, oldValue);
  });

  $scope.changeLanguage = function() {
    console.log("language changed: " + $scope.selectedLanguage)
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="Ctrl">
  <select class="form-control" ng-change="changeLanguage()" ng-model="selectedLanguage" ng-options='lang.key as lang.name for lang in languages'></select>
  <p>{{selectedLanguage}}</p>
</div>