Reputation: 1892
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:
Note: Here I attached only one input but I have multiple input fields. Also, In save function I had logic data save into database.
Upvotes: 4
Views: 8866
Reputation: 24901
You can use $pristine
to identify if there were any changes to the form and enable button only then:
<body ng-controller="MainCtrl">
<form name="myForm">
<input name="myText" type="text" name="test" ng-model="mytext" required />
<button ng-click="save(myForm)" ng-disabled="myForm.$invalid || myForm.$pristine">Save</button>
</form>
</body>
Notice how $pristine
is used on ng-disabled
:
ng-disabled="myForm.$invalid || myForm.$pristine"
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
:
$scope.save = function(myForm) {
// set form to pristine
myForm.$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
:
ng-click="save(myForm)"
Here is JSFiddle that demonstrates the functionality
For more information check out documentation of FormController.
Upvotes: 5
Reputation: 3369
Well here is how i would do it, i'll add another tracking variable. something like this.
$scope.btnStatus = true;
$scope.save = function(){
//logic or http method
$scope.btnStatus = false;
console.log("Test");
}
$scope.onChange = function(){
if($scope.btnStatus == false)
$scope.btnStatus = true;
}
and the html would look like this.
<form name="myForm">
<input name="myText" type="text" name="test" ng-change="onChange()" ng-model="mytext" required />
<button ng-click="save()" ng-disabled="myForm.$invalid || !btnStatus">Save</button>
</form>
Here is a working code based off of your code.
Upvotes: 0
Reputation: 9794
you have disabled the submit button when the form is invalid.
myForm.$invalid
so whenever a required field is blank the form will be invalid and button will be disabled. As soon as all the required input in the form have values, submit button will be enabled.
To make it disabled you need to reset all the modal variables of the required inputs once the save has done its work i.e on the success call back of http request reset the model variables.
Upvotes: 0