是否可以使用标准的Angular机制,在错误标志本身的同时存储一些额外的数据?即我手动设置ngModel.$setValidity
,我想传递一些数据以及错误标志,以显示在ngMessages
指令中。例如,让我们假设字段的最小/最大长度取决于一些外部因素,因此计算为&服务器端进行验证。服务器响应customlength
错误代码以及max
和min
属性,我希望将其显示给用户。目前我只是简单地设置ngModel.$setValidity("customlength", false);
,但我想传递{max: response.max, min: response.min}
,在模板中插入<div ng-message="customlength">the length should be between {{ data.min }} and {{ data.max }}
我想传递{max: response。Max, min:响应。Min}沿,要在模板中插值的长度应该在{{数据之间。Min}}和{{数据}。马克斯}}
使用根作用域存储打算在消息字符串中输出的值:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-messages.js"></script>
<script>
angular.module('ngMessagesExample',['ngMessages']);
</script>
<body ng-app="ngMessagesExample">
<form name="myForm" id="{{$root.$id}}">
<label>
<p>Enter Min:<input type="text" ng-model="form_min">
<p>Enter Max:<input type="text" ng-model="form_max">
<p>Enter your name:
<input type="text"
name="myName"
ng-model="name"
ng-minlength="form_min"
ng-maxlength="form_max"
required />
</label>
<p>
<input type="radio" required name="foo" ng-model="foo" value="1">Yes
<input type="radio" required name="foo" ng-model="foo" value="2">No
</p>
<p>
Foo: <input type="text" ng-model="myForm.foo.$modelValue">
</p>
<p>
<input type="submit" value="{{myForm.foo.$error.required ? 'No' : 'Yes'}}">
</p>
<pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>
<div ng-messages="myForm.foo.$error" style="color:maroon" role="alert">
<div ng-message="required">Pick one</div>
</div>
<div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
<div ng-message="required">Your value should be between {{form_min}} and {{form_max}} characters long</div>
<div ng-message="minlength" id="{{$id}}">Your value is less than {{form_min}}</div>
<div ng-message="maxlength" id="{{$id}}">Your value is greater than {{form_max}}</div>
</div>
</form>
</body>
引用
- 在AngularJS中使用ngMessages - SitePoint进行简单的表单验证
AngularJS:开发者指南:从以前的版本迁移
显式地为DOM元素提供ng-model | to THE NEW Blog
使用NgModelController自定义指令