如何使用ng-disabled来阻止用户重新提交表单

时间:2016-01-06 06:37:22

标签: javascript angularjs

我试图阻止用户使用下面的代码重新提交登录表单

<button class="submit" ng-disabled="form_login.$submitted" type="submit"></button>

但是,只要单击该按钮,即使用户提交了无效数据,也会禁用提交按钮。在提交有效信息后,停止提交按钮的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

虽然你的问题不明确,但你可以试试这个,

这是HTML:

<form action="#" method="post">
  Name::<input type="text" ng-model="name" ng-keyup="dirty()">
  Address::<input type="text" ng-model="address" ng-keyup="dirty()">
  <input type="submit" ng-disabled="error" value="Submit">
 </form>

这是JS:

angular.module('myApp', []).controller('ctrl', function($scope){

     $scope.error = true;  //Disables button initially

     $scope.dirty = function(){
         if($scope.name!='' && $scope.address!='')//Check conditions here
          {
            $scope.error = false;  //Enables the button
          } 
     }
});

答案 1 :(得分:0)

您可以使用ng-required属性(directive)来检查元素的dirty状态。

试试这个:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <form action="#" method="post" name="myForm">
    Name::
    <input type="text" ng-model="name" ng-required='true'>
    <input type="submit" ng-disabled="myForm.$invalid" value="Submit">
  </form>
</body>

</html>

Live example