Angularjs select ng-change is not triggered when ng-model is initialized in controller

Rodrigo Cifuentes Gómez picture Rodrigo Cifuentes Gómez · Jul 4, 2014 · Viewed 11.6k times · Source

I have my select like so

<select ng-model="id_select" ng-options="fide.id as fide.name for fide in fides" ng-change="loadInfo()">
   <option value="" selected disabled>Seleccionar</option>
</select>

And in my controller I have this

RestService.getFides().then(function(fides){

   $scope.id_select = fides;
   if(typeof $rootScope.selected_id !== 'undefined')
   {
      $scope.id_select = $rootScope.selected_id
   }
});

$scope.loadInfo = function() {
  alert("triggered!!");
}

My select is loading as expected with fides but when I try to set my select value with $rootScope's value ng-change function loadInfo() is not triggered but when I select in my view it works fine.

Any ideas of what am I doing wrong?

Thank you all in advance for your help :)

Answer

Terry picture Terry · Jul 4, 2014

From the documentation for ngChange:

Evaluate the given expression when the user changes the input. The expression is evaluated immediately, unlike the JavaScript onchange event which only triggers at the end of a change (usually, when the user leaves the form element or presses the return key). The expression is not evaluated when the value change is coming from the model.

You need to call your event handler manually if you are changing the model programatically:

if (typeof $rootScope.selected_id !== 'undefined') {
  $scope.id_select = $rootScope.selected_id;
  $scope.loadInfo();
}