2

我试图弄清楚如何通过单击按钮来使用 ng-message。我发现的大多数文档都会根据输入而不是按钮自动显示错误消息。我会改变什么,以便在单击按钮后显示 ng-messages。这是我的代码

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

2 回答 2

0

您可以使用具有属性的ng-show角度指令$submittedng-form

将此添加到您的代码中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>

你可以在这里看到一个工作小提琴。希望这会有所帮助


或者或者像这样在每条消息中添加显示

    <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>
于 2016-07-29T22:33:54.497 回答
0

您可以在带有 ngIf 的表单控制器上使用 $submitted 标志:

<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>
于 2016-07-29T22:07:57.523 回答