我是AngularJS的新手,所以这可能是一个非常愚蠢的问题。
通过使用Angular documentation on ngMessages,我想实现在满足某些要求时显示的消息框。
但是,即使使用复制粘贴示例,即使未满足其要求,也不会隐藏消息框。但是,$error
变量确实显示了正确的值。
angular.module('ngMessagesExample', ['ngMessages']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
<form name="myForm">
<label>
Enter your name:
<input type="text" name="myName" ng-model="name" ng-minlength="5" ng-maxlength="20" required />
</label>
<pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>
<ng-messages for="myForm.myName.$error" style="color:maroon;" role="alert">
<ng-message when="required">You did not enter a field</ng-message>
<ng-message when="minlength">Your field is too short</ng-message>
<ng-message when="maxlength">Your field is too long</ng-message>
</ng-messages>
</form>
答案 0 :(得分:5)
以下是您问题的替代解决方案。
<p ng-if="myForm.myName.$error.minlength">Your field is too short.</p>
<p ng-if="myForm.myName.$error.maxlength">Your field is too long.</p>
<p ng-if="myForm.myName.$error.required">You did not enter a field.</p>
答案 1 :(得分:4)
您的代码很好,在我看来您只需要单独导入ngMessages模块。 (您是否检查过控制台是否有错误?)
请记住,我将脚本标记移动到 body 标记的底部以获得更好的性能,但它也可以在标题中正常工作。
<body ng-controller="MainCtrl">
<form name="myForm">
<label>
Enter your name:
<input type="text" name="myName" ng-model="name" ng-minlength="5" ng-maxlength="20" required />
</label>
<pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>
<ng-messages for="myForm.myName.$error" style="color:maroon;" role="alert">
<ng-message when="required">You did not enter a field</ng-message>
<ng-message when="minlength">Your field is too short</ng-message>
<ng-message when="maxlength">Your field is too long</ng-message>
</ng-messages>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.1/angular-messages.min.js"></script>
<script src="app.js"></script>
答案 2 :(得分:0)
<div ng-if="myForm.myName.$touched" for="myName" ng-messages="myForm.myName.$error" style="color:maroon;" role="alert">
<ng-message="required">You did not enter a field</ng-message>
<ng-message="minlength">Your field is too short</ng-message>
<ng-message="maxlength">Your field is too long</ng-message>
</div>
Remove when
from your code.