当输入文本为空时,Angular JS禁用按钮

时间:2018-02-15 14:04:29

标签: javascript angularjs

我从角度JS开始,我想在输入文本"登录"时禁用(属性" ng-disabled")按钮和#34;密码"是空的。问题是,默认情况下输入文本"登录"是"登录"和输入文本"密码"是" PASSWORD",所以我的输入永远不会是空的......

帮助,

由于

1 个答案:

答案 0 :(得分:3)

只需使用占位符,而不是使用

填充它

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.pass = ""; // empty, instead of "PASSWORD"
  $scope.foo = () => {
    console.log($scope.pass);
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <input placeholder="PASSWORD" ng-model="pass">
  <button ng-click="foo()" ng-disabled="!pass">Sign in</button>
</div>

这是另一个适合您的描述的示例,您可以使用某些文本填充它,但仍然禁用该按钮。它使用ng-focus重置输入字段(如果已选中),并且具有$dirty检查,仅允许在输入被更改/更改时按下按钮。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.pass = "PASSWORD";
  $scope.foo = () => {
    console.log($scope.pass);
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <form name="form">
    <input ng-focus="pass=''" name="pass" ng-model="pass">
    <button ng-click="foo()" ng-disabled="!form.pass.$dirty || !pass">Sign in</button>
  </form>
</div>