Angularjs + Disable and Enable submit button

I have an example code:

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 code in this link: Click here

Logics:

  • The save button is disabled by default.
  • After entering the form, enable the button.
  • After saving, turn off the save button again.
  • Again, the user enters text to enable the save button.

Note. Here I attach only one input, but I have several input fields. In addition, in the save function, I saved the logical data in the database.

+4
source share
3 answers

You can use $pristineto determine if there were any changes in the form and the power 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>

, $pristine ng-disabled:

ng-disabled="myForm.$invalid || myForm.$pristine"

, .

, . $setPristine:

$scope.save = function(myForm) {
    // set form to pristine
    myForm.$setPristine();
}

, , . HTML ng-click:

ng-click="save(myForm)"

JSFiddle,

FormController.

+4

, .

myForm.$invalid

, , , . , .

, reset , , http- reset .

0

Well, how would I do this, add another tracking variable. something like that.

$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 html will 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 the valid code based on your code.

-1
source

Source: https://habr.com/ru/post/1664091/


All Articles