简体   繁体   中英

Angular: why ng-submit after ng-blur is not working?

In this plunk , if you click on the second field, then click on Submit, you will see that the form was not submitted (See that variable {{submitted}} is still false). ng-blur works fine, as the error message is displayed telling that the field is empty. Why ng-submit is not triggered?

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>

Javascript

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;
  };

});

The answer is that the button was pushed down when the error message appeared, so it was never really clicked. Aligning the message to the field (ie the button stayed on the same place without moving and therefore it was clicked) with style="float:right" fixed the problem:

  <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM