jrharshath
jrharshath

Reputation: 26583

In Angular, how do you check if a form (or its elements) have changed in value?

I'm aware of properties like $pristine, $dirty etc. However, $dirty simply indicates if that form element has been interacted with.

How do I check if that form element has been actually changed?

I need something like a $changed property on the element that indicates if the value of that input (or in the case of a form, any child input) has been updated. If the value is set back to the original value, I want $changed to be set back to false.

My question: does angular have something like this already? If not, how do I go about building such functionality?

Upvotes: 2

Views: 3663

Answers (2)

Enkode
Enkode

Reputation: 4783

You will need to store the form data, watch and then compare. This directive seems to that does that with a "modified" property which sounds like your "changed" property you are looking for. They have a plunker to test.

You could use a watch but if you want to re-use the code repeatedly you will need to create a directive to do the heavy lifting.

https://github.com/betsol/angular-input-modified

Upvotes: 2

Brian Baker
Brian Baker

Reputation: 996

You can use $watch like so:

In your controller:

$scope.$watch('myForm', function(){
 console.log('Form Changed')
},true)

In your HTML:

<form name='myForm'>
        <input type="text" placeholder="Enter new name" ng-model="myForm.inputText" />
        <input type="text" placeholder="Other" ng-model="myForm.inputOther" />
        <input type="submit" />
    </form>

Upvotes: 0

Related Questions