G. Deward
G. Deward

Reputation: 1592

Form-level ng-change in Angular?

How can I check for any field changes in a form? I would like to only enable a Save button if the underlying object has changed. Currently, I'm adding a ng-change="vm.formChanged()" attribute to every single field on the form. I would much rather do this once at the form level and not decorate every single field.

My method looks something like this:

formChanged () {
  vm.hasChanges = (JSON.stringify(vm.item) != JSON.stringify(vm.original));
}

... and I'm binding the Save button to ng-disabled="!vm.hasChanges".

Upvotes: 0

Views: 380

Answers (2)

Steve
Steve

Reputation: 1095

Assuming you have given a name to your form you could do something like this:

<form name="myForm">
  <input type="text" ng-model="form.name">
  <input type="text" ng-model="form.age">
  <button ng-disabled="myForm.$pristine">Submit</button>
</form>

This will just disable the button as long as the form is pristine. Once the model has changed it will enable the submit button. However, note, if you undo your change to a field, the button will still be enabled since angular assumes the form is no longer pristine.

Here is a link to a working example: http://plnkr.co/edit/RYJIrZ3m4b8jmd0oVIuh?p=preview

Upvotes: 1

Charles
Charles

Reputation: 180

You can use "yourForm.$pristine" to check if form has been monified

Upvotes: 0

Related Questions