Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngChange is called when model changed programmatically

I have a problem when angular's ng-change is called when model is changed programmatically.

$scope.sendMessage = function() {
    $scope.message = "Message sent";
}

$scope.confirmed = true;
$scope.mySelectBox = $scope.selects[1];

<select ng-model="mySelectBox"
        ng-options="item.name for item in selects track by item.name"
        ng-change="sendMessage()">
</select>

Here is code example: http://plnkr.co/edit/R4MO86ihMrauHXhpCMxi?p=preview

Message should be null, because sendMessage shouldn't be called. Model is changed programmatically.

like image 986
divide by zero Avatar asked Jun 15 '15 13:06

divide by zero


2 Answers

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.

like image 116
kTT Avatar answered Sep 28 '22 03:09

kTT


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";
    }
}
like image 44
Tomek Sułkowski Avatar answered Sep 28 '22 03:09

Tomek Sułkowski