ngChange doesn't work when the model is changed programmatically?

All we need is an easy explanation of the problem, so here it is.

It says in the docs that ngChange will not fire: “if the model is changed programmatically and not by a change to the input value”.

Does this mean that if you ever change the model programmatically, you can’t use ngChange?

Or does it mean that you can’t use ngChange if:

1) You change the model programmatically

AND

2) You’re unable to change the model via the input field

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

It just means that the ngChange expression won’t be evaluated if javascript is used to change the model. If you wanted ngChange to fire you would need to programmatically call the expression similar to the following:

<input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />

You would need to manually call the change function if you wanted it to fire:

$scope.confirmed = 'test';
$scope.change();

Method 2

If I read and understand this correctly, unfortunatelly you can’t do it with ng-change as you say, but I’m not 100% sure.

I was thinking about ng-model-options, a new feature that came with AngularJS 1.3 and maybe this can push you forward.

There is an automatical options for getters and setters that allows you to change the model in real time. Theoretically, you could use this and call your update function with ng-bind.

Maybe this can be your possible solution to solve your problem…

(function(angular) {
  'use strict';
angular.module('getterSetterExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    var _name = 'Brian';
    $scope.user = {
      name: function(newName) {
        return angular.isDefined(newName) ? (_name = newName) : _name;
      }
    };
  }]);
})(window.angular);
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-ngModelOptions-directive-getter-setter-production</title>
  

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
  <script src="app.js"></script>
  

  
</head>
<body ng-app="getterSetterExample">
  <div ng-controller="ExampleController">
  <form name="userForm">
    Name:
    <input type="text" name="userName"
           ng-model="user.name"
           ng-model-options="{ getterSetter: true }" />
  </form>
  <pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
</body>
</html>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply