如果输入为空,则应禁用一个按钮,但另一个按钮也会受到影响

时间:2017-04-29 19:28:45

标签: html angularjs forms

我正在尝试编写登录/注册页面,如果未填写(登录名和密码)字段,则禁用“登录”按钮。然而,它也是“注册”按钮的感情,它也要求填写字段。

我不确定是什么导致这种情况,并且从标签中删除“所需的ng-model”会阻止登录按钮使用“ng-disabled”。有人可以帮我理解造成这种行为的原因吗?

<div class = "form-group" aling="center">
  <label for="exampleInputEmail" >&nbsp; Usuário &nbsp;</label>
  <input type='text' placeholder = 'Usuário'
     class="form-control" required ng-model = "user">
  <div class="form-group">
     <label for="exampleInputPassword">&nbsp; Senha &nbsp; &nbsp;&nbsp;&nbsp;</label>
     <input type='password' placeholder = 'Senha'
        class="form-control" required ng-model = "password">
  </div>
  <p>
  <div class="main" ng-controller="loginController">
     <button class="btn btn-default" type="submit" 
        ng-disabled="form1.$invalid" ng-click="login(user,password)">
     Login</button>
  </div>
  <button href="#" class="btn btn-default" type="submit" 
     ng-click="register()">
     Register
  </button>
  <p></p>

3 个答案:

答案 0 :(得分:1)

目前发生的情况是,当您点击Register按钮时,它会尝试提交表单。您应该将type="submit"按钮的Register更改为type="button"。即使您没有在按钮上指定任何type,也会将其视为type="submit"

<button class="btn btn-default" type="button" ng-click="register()">
     Register
</button>

答案 1 :(得分:1)

您注册按钮与所有其他字段的格式相同,并且类型为submit,由于两个输入为required,因此会自动禁用提交按钮

答案 2 :(得分:0)

一些观察结果:

  • 您只为loginController按钮定义控制器Login。因此,usernamelogin字段超出了此控制器的范围。
  • 在DOM中的父元素(表单外部)中定义控制器。

<强>样本

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

app.controller("loginController", function($scope) {

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="loginController">
<form name="myForm" novalidate>
<div class = "form-group" aling="center">
  <label for="exampleInputEmail" >&nbsp; Usuário &nbsp;</label>
  <input type='text' placeholder='Usuário'
     class="form-control" required ng-model="user">
  <div class="form-group">
     <label for="exampleInputPassword">&nbsp; Senha &nbsp; &nbsp;&nbsp;&nbsp;</label>
     <input type='password' placeholder='Senha'
        class="form-control" required ng-model="password">
  </div>
  <p>
  <div class="main">
     <button class="btn btn-default" type="submit" 
        ng-disabled="myForm.$invalid" ng-click="login(user,password)">
     Login</button>
  </div>
  <button href="#" class="btn btn-default" type="submit" ng-click="register()">Register
  </button>
  </div>
  </form>
</div>