角度:为什么ng-blur之后的ng-submit不起作用



在此 plunk 中,如果您单击第二个字段,然后单击提交,您将看到表单未提交(请参阅变量 {{submitted}} 仍然是假的)。 ng-blur 工作正常,因为显示错误消息,告知该字段为空。为什么没有触发 ng-submit?

.HTML

<body ng-app="ngMessagesExample" ng-controller="ctl">
  <form name="myForm" novalidate ng-submit="submitForm()">
  <label>
    Enter Aaa:
    <input type="text"
           name="aaa"
           ng-model="aaa"
           ng-minlength="2"
           ng-maxlength="5"
           required ng-blur="aaaBlur()" />
  </label>
  <div ng-show="showAaa || formSubmitted" ng-messages="myForm.aaa.$error" 
       style="color:red" role="alert">
    <div ng-message="required">You did not enter a field</div>
    <div ng-message="minlength">Your field is too short</div>
    <div ng-message="maxlength">Your field is too long</div>
  </div>
  <br/>
  <label>
    Enter Bbb:
    <input type="text"
           name="bbb"
           ng-model="bbb"
           ng-minlength="2"
           ng-maxlength="5"
           required ng-blur="bbbBlur()" />
  </label> <--- click here, then click Submit
  <div ng-show="showBbb || formSubmitted" ng-messages="myForm.bbb.$error" 
       style="color:green" role="alert">
    <div ng-message="required">You did not enter a field</div>
    <div ng-message="minlength">Your field is too short</div>
    <div ng-message="maxlength">Your field is too long</div>
  </div>
  <br/>
  <button type="submit">Submit</button>
</form>
submitted:{{formSubmitted}} showAaa:{{showAaa}} showBbb:{{showBbb}}
</body>

爪哇语

var app = angular.module('ngMessagesExample', ['ngMessages']);
app.controller('ctl', function ($scope) {
  $scope.formSubmitted = false;
  $scope.showAaa = false;
  $scope.showBbb = false;
  $scope.submitForm = function() {
    $scope.formSubmitted = true;  
  };

   $scope.aaaBlur = function() {
    $scope.showAaa = true;
  };  
   $scope.bbbBlur = function() {
    $scope.showBbb = true;
  };
});

答案是当出现错误消息时按钮被按下,因此从未真正单击过。将消息与字段对齐(即按钮停留在同一个位置而不移动,因此被单击)与style="float:right"解决了问题:

  <div style="float:right" ng-show="showAaa || formSubmitted" 
        ng-messages="myForm.aaa.$error" style="color:red" role="alert">
    <div ng-message="required">You did not enter a field</div>
    <div ng-message="minlength">Your field is too short</div>
    <div ng-message="maxlength">Your field is too long</div>
  </div>

最新更新