NgChange doesn't work when model changes programmatically?

The docs say: ngChange does not work: "if the model is changed programmatically, and not by changing the input value."

Does this mean that if you ever change the model programmatically, you cannot use ngChange ?

Or that means you cannot use ngChange if:

1) You programmatically change the model

and

2) You cannot change the model through the input field

+6
source share
2 answers

It just means that the ngChange expression will not be evaluated if javascript is used to modify the model. If you want ngChange to work, you need to programmatically call an expression like the following:

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

You will need to manually call the change function if you want to run it:

 $scope.confirmed = 'test'; $scope.change(); 
+9
source

If I read and understand this correctly, unfortunately, you cannot 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 are automatic parameters for getters and setters that allow you to change the model in real time. Theoretically, you can use this and call the update function using ng-bind.

Perhaps this may 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> 
+1
source

Source: https://habr.com/ru/post/979815/


All Articles