0

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".

G. Deward
  • 1,542
  • 3
  • 17
  • 30

2 Answers2

1

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

Steve
  • 1,105
  • 7
  • 20
  • Tried this at first but could not get `ng-disabled="myForm.$invalid || (myForm.$pristine && mySecondForm.$pristine)"` to work with multiple conditions. – G. Deward Mar 07 '16 at 16:05
  • The `mySecondForm` is a grandchild and is populated after two other promises. – G. Deward Mar 07 '16 at 16:10
  • Do you have a plunker: http://plnkr.co/edit/tpl:8rFfZljYNl3z1A4LKSL2 as an example of how your html is structured once all promises have been resolved? This would help to work out what is happening – Steve Mar 07 '16 at 16:18
  • This could also be an issue caused by having nested forms, since I would assume that any changes that cause a child to be `$dirty` would cause the parent to be `$dirty` too. Since there is a kind of inheritance happening here. – Steve Mar 07 '16 at 16:21
  • As a note, it seems that you cannot create nested forms according to the HTML spec: http://stackoverflow.com/questions/379610/can-you-nest-html-forms – Steve Mar 07 '16 at 16:27
  • The forms are not nested, however there are two on the page. – G. Deward Mar 08 '16 at 00:13
0

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

Charles
  • 170
  • 11
  • Can't... so far. Two forms on the page (not nested). The Save button points to a function call but uses objects bound to both forms. For some reason, `$pristine` won't work while evaluating both forms: `ng-disabled="myForm.$invalid || (myForm.$pristine && mySecondForm.$pristine)"`. – G. Deward Mar 08 '16 at 14:26