Tushar
Tushar

Reputation: 1123

AngularJS : Detect form changes

I'm developing an angular app, where I have to check the form changes, and perform some operation depending upon the changes. I know, this can be achieved using $scope.watch but that would cost me performance.

What I'm trying to achieve

I've a pre-populated form and I will take the form data as a reference using angular.copy() and compare with original data.

I had also tried $parsers to check, but failed. So, is there any way to accomplish this?

Upvotes: 3

Views: 8449

Answers (3)

Michael Kang
Michael Kang

Reputation: 52847

When you compare the copied object against the original form data, and you want to check for changes, you can use angular.equals.

 angular.equals(formObj, formObjCopy)

This will do a deep compare of the object and its nested sub-properties, and return true if the object hasn't changed.

Upvotes: 1

AlainIb
AlainIb

Reputation: 4708

Did you try with ng-change ? It call a function when value of ng-model change

<input type="search"  ng-change="changeValue()"  ng-model="test" name="test"/>

If you want to know wich field call the function you can add the name as string parameter

<input type="search"  ng-change="changeValue('field1')"  ng-model="field1" name="field1"/>

In the controller don't forget to put the function changeValue in the scope

 $scope.changeValue = function(fieldname){
    switch (fieldname){
        case 'field1' : .... break;
        case 'field2' : .... break;     
        case 'field3' : .... break;
        ...
    }
 }

Upvotes: 3

Daniel Kobe
Daniel Kobe

Reputation: 9825

You can use ng-change.
From the docs - "Evaluate the given expression when the user changes the input. The expression is evaluated immediately, unlike the JavaScript onchange event which only triggers at the end of a change (usually, when the user leaves the form element or presses the return key)."
Difference between ng-change and $watch

Upvotes: 6

Related Questions