I have sample code like this:
Html Code:
<body ng-controller="MainCtrl">
<form name="myForm">
<input name="myText" type="text" name="test" ng-model="mytext" required />
<button ng-click="save()" ng-disabled="myForm.$invalid">Save</button>
</form>
</body>
Js code:
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.save = function(){
//logic or http method
console.log("Test");
}
});
Attached the code in this link: Click Here
Logic:
- Default save button disabled.
- After enter the form enable the button.
- After save again disable the save button.
- Again user enter the text need to enable save button.
Note: Here I attached only one input but I have multiple input fields.
Also, In save function I had logic data save into database.
Best Answer
You can use
$pristine
to identify if there were any changes to the form and enable button only then:Notice how
$pristine
is used onng-disabled
:In this case button will be disabled if form is invalid or if there were no changes to the form.
If you use this approach you also need to set the form to pristine after saving the data. You can use method
$setPristine
:Notice that there is a form parameter which is used to pass a form to the method. In HTML you also need to pass this parameter as part of
ng-click
:Here is JSFiddle that demonstrates the functionality
For more information check out documentation of FormController.