Javascript – Angularjs + Disable and Enable submit button

angularjsjavascriptvalidation

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:

  1. Default save button disabled.
  2. After enter the form enable the button.
  3. After save again disable the save button.
  4. 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:

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