Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 519
Adam Zerner Avatar asked Dec 17 '14 23:12

Adam Zerner


2 Answers

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();
like image 94
Wayne Ellery Avatar answered Nov 15 '22 06:11

Wayne Ellery


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>
like image 26
arman1991 Avatar answered Nov 15 '22 06:11

arman1991