在必填字段为空时使用ng-disable

时间:2016-11-15 16:54:03

标签: javascript angularjs forms angularjs-scope

我有一些问题要让ng-disable投入使用,所以,我有这个div:

<div>
  <p>{{ message }}</p>
  <div >
     <input type="number" id="field1" placeholder="field 1" ng-model="field1" min="0" required>
     <input type="date" id="field2"  ng-model="field2">
  </div>
  <button ng-disabled="field1.$valid" ng-click="submit()">OK</button>
</div>

我想验证如果field1为空(未填充)我想禁用按钮,那么,用户无法点击它。

我怎么能这样做?
我尝试了一些方法,但任何人都为我工作。

1 个答案:

答案 0 :(得分:2)

您应该将您的HTML代码放在form中。点击Run code snippet即可查看其效果。

&#13;
&#13;
function ApplicationController($scope) {     
    $scope.message = "Hola Pedro Henrique!";
    $scope.submit = function(){
        console.log($scope.field1);
    };
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app ng-controller="ApplicationController" role="form" name="form1" novalidate>
    <p>{{ message }}</p>
    <div>
        <input type="number" id="field1" placeholder="field 1" ng-model="field1" min="0" required>
        <input type="date" id="field2"  ng-model="field2">
    </div>
    <button type="submit" ng-disabled="form1.$invalid" ng-click="submit()">OK</button>
</form>
&#13;
&#13;
&#13;