2016-07-29 76 views
2

我想弄清楚如何使用基於按鈕單擊的ng消息。我找到的大多數文檔都會自動顯示基於輸入而不是按鈕的錯誤消息。我會更改什麼,以便在單擊按鈕後顯示ng-messages。這裏是我的代碼使用按鈕驗證ng消息

<div ng-controller="userController"> 
    <div class=user> 
     <form name="login"> 
      <h2 class>Login</h2> 
      <h3 class = "login_page">UserName</h3> 
      <input ng-model="user" type="text" ng-minlength="1" required> 
      <h3 class = "login_page">Password</h3> 
      <input ng-model="password" type="password" name="password" ng-minlength="4" required> 
      <input type="submit" value="Login" ng-click="login()" > 
      <div ng-messages="login.password.$error" style="color:maroon" role="alert"> 
       <div ng-message="required">You did not enter a field</div> 
       <div ng-message="minlength">Your field is too short</div> 
      </div> 
     </form> 
    </div> 
</div> 

回答

0

可以將表單控制器ngIf上使用$提交標誌:

<div ng-if="login.$submitted" ng-messages="login.password.$error" style="color:maroon" role="alert"> 
    <div ng-message="required">You did not enter a field</div> 
    <div ng-message="minlength">Your field is too short</div> 
</div> 
0

可以使用ng-show指令的角度與ng-form

$submitted屬性添加這您的代碼ng-show="login.$submitted"

<input type="submit" value="Login" ng-click="login()" > 
    <div ng-show="login.$submitted" ng-messages="login.password.$error" style="color:maroon" role="alert"> 
     <div ng-message="required">You did not enter a field</div> 
     <div ng-message="minlength">Your field is too short</div> 
    </div> 

你可以看到一個工作小提琴here。希望這將有助於


或者另外增加顯示每封郵件這樣

<div ng-messages="login.password.$error" style="color:maroon" role="alert"> 
     <div ng-show="login.$submitted" ng-message="required">You did not enter a field</div> 
     <div ng-show="login.$submitted" ng-message="minlength">Your field is too short</div> 
    </div>