Angularjs select ng-change is not triggered when n

2019-07-01 15:17发布

问题:

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 :)

回答1:

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();
}