james managbanag james managbanag - 1 year ago 65
AngularJS Question

How to disabled a button[update] when there is no changes in a form

<form role="form" id="myForm" name="myForm">
<input class="form-control" ng-model="firstName" type="text" />
<input class="form-control" ng-model="lastName" type="text" />

<button class="btn btn-info" ng-disabled="myForm.$pristine">cancel</button
<button class="btn btn-primary" ng-disabled="myForm.$pristine">update</button

assume that there is a list of data in a table. and when i click a data a modal will pop up with data on it(in the example the firstName and lastName). inside the modal, there’s an EDIT button that when u click it two another buttons will appear(CANCEL and UPDATE) I want to set the update button disabled while there is no changes yet happening in the FORM. By using $pristine i found a solution on that. but there’s one problem. when i try to edit the data and decide to cancel it(reset the current data) the nxt time i click EDIT the UPDATE button is already enabled even i dont have changes in my data yet. is there any solution for this? thank you mate!

Answer Source

On cancel set the form to pristine. This will set $pristine back to true which should disable the buttons.

<button class="btn btn-info" ng-disabled="myForm.$pristine" ng-click="myForm.$setPristine()">cancel</button

For cancel buttons I add a function in the controller to reset all fields and then set the form back to pristine which effectively resets the form.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download