ngChange is called when model changed programmatically

感情迁移 提交于 2019-12-03 12:35:13

According to docs, you're right.

https://docs.angularjs.org/api/ng/directive/ngChange

but this seems to be a bug caused by the order in which the events are hooked up

The best way round it - with resorting to js handler (onchange)

$scope.$watch("mySelectBox", function(a,b) {
    if (a.name!=b.name) {
       $scope.message = "Message sent! (old="+b.name+', new='+a.name+')';
    }
  });

See plunk http://plnkr.co/edit/2ZbxS1tszppR9SrNqxVB?p=preview

HTH

You can try with ngModelOptions. See this plunker for reference http://plnkr.co/edit/BdKx62RW5Ls2Iz1H3VR1?p=preview.

In my example I used ng-model-options="{ updateOn: 'change', debounce: { change: 0 } }" and it seems to work. It only runs function provided in ngChange when I change the selection. On initialize phase message stays empty.

The ng-change callback is changed on each model change, and it treats the initial setup as such change. What you might want to do is to run desired code only after user interacts with it. You can check the $touched property of the field:

<form name="exampleForm" ng-controller="ExampleController">
  <select ng-model="mySelectBox" name="mySelectBox"
          ng-options="item.name for item in selects track by item.name"
          ng-change="sendMessage()">
  </select>
  <p>message = {{message}}</p>
</form>


$scope.sendMessage = function() {
    if ($scope.exampleForm.mySelectBox.$touched) {
        $scope.message = "Message sent";
    }
}

You are providing value to model in controller ,so whenever you will set value of model which is matching with list it will call ng-change:

See updated plunker: http://plnkr.co/edit/f3xGmKesLFbzti56WLyH?p=preview

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