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

泪湿孤枕 提交于 2019-12-12 17:03:39

问题


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


来源:https://stackoverflow.com/questions/24579186/angularjs-select-ng-change-is-not-triggered-when-ng-model-is-initialized-in-cont

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!