0

Well, the title of question might not be clear. So here I explain:

I have an input field I1 whose ng-model is binded to an object.

Then I have few more input fields, whose values if changed are summed together and reflected in ng-model of I1.

Now when, the I1 is changed explictly by typing in input box, its ng-change gets triggered. However, if the value of I1 changes due to change in few more input fields, the ng-change of I1 is not triggered.

In short, the value displayed in I1 is changed due to changes in few more input fields, but its ng-change is not triggered.

How do I trigger ng-change, even when ng-model is soft updated I hope, readers get the idea here, as I know it has become bit complicated to read

Saurabh Tiwari
  • 4,632
  • 9
  • 42
  • 82
  • Please share related code for better understanding. – ssilas777 Oct 06 '15 at 07:21
  • the reading complication can be reduced if you share the code – harishr Oct 06 '15 at 07:30
  • if you wanna trigger an event when model value of field **I1** is changed you probably should use the `$watch` function. – Michael Oct 06 '15 at 07:31
  • Did you find any answer for this issue? – Arashsoft Mar 20 '17 at 18:02
  • Well I guess, this was not an issue at all. It is the expected behavior of `ng-change`. It triggers only when user changes the model explicitly. The correct way to achieve will be using a $watch as suggested by Rabi, Chetan and Michael. I wonder how I missed to select one of them as correct answer. – Saurabh Tiwari Mar 22 '17 at 06:15

2 Answers2

0

Get the idea from below example:-

function MyController($scope) {

$scope.modelVar = 1;

$scope.$watch('modelVar', function() {

     alert('hey, modelVar has changed!');

  // here you can call onChange event.

});

}

Chetan Sharma
  • 334
  • 2
  • 11
0

You can use a watch on your model and achive your desired result -

HTML

<input type="text"  ng-model="l1" ng-change="doSomething()" />

Controller

$scope.$watch(function() { return $scope.l1;}, 
       function(newVal, oldVal) {
         if (newVal !== oldVal) {
             $scope.doSomething();
         }
});

Alternatively, you can look at this thread - How to trigger ng-click [AngularJS] programmatically

But the first approach is recommended.

Community
  • 1
  • 1
Rabi
  • 2,210
  • 17
  • 18
  • Thanx Rabi and Chetan as both suggested same approach. However, how is it possible to use $emit in this case, I just realized that **few more input fields** are within the ng-repeat of the div where I1 is.**. Can I fire a `$emit('ng-change', arguments)` or something like this to propagate the change upwards – Saurabh Tiwari Oct 06 '15 at 09:35
  • yes, you can. But if the operation is on same controller, you wouldn't want to emit an event, watch would suffice your need. – Rabi Oct 06 '15 at 09:44