尝试通过包装到自定义指令并显示消息来最小化为显示ngmessages模块而编写的HTML。
我写的下面的实现似乎工作得很好。我的挑战是使其可重用和动态。
angular.module('app').directive('myNgMsg', function () {
var tpls ='<div ng-messages="form.field1.$error" ng-if="form.field1.$touched" style="color:red;font-weight: bold;" role="alert">'+
'<div ng-message="required" class="error-message">Required Field</div>'+
'<div ng-message="pattern">Invalid Input</div>'+
'<div ng-message="minlength" class="error-message" >minimum 5</div>'+
'<div ng-message="maxlength" class="error-message" >Maximum 10</div></div>';
return {
restrict: 'E',
replace: true,
transclude: true,
template: tpls
}
});
HTML
<div class="form-group">
<label astr>request num</label>
<input type="text" name="field1"class="form-control" required ng-minlength="5" ng-pattern="/^[-a-zA-Z0-9@\.+_]+$/" ng-model="ngObject.request.field1"/>
<my-ng-msg> </my-ng-msg>
</div>
<div class="form-group">
<label astr>name</label>
<input type="text" name="field2"class="form-control" required ng-minlength="5" ng-pattern="/^[-a-zA-Z0-9@\.+_]+$/" ng-model="ngObject.request.field2"/>
<my-ng-msg> </my-ng-msg>
</div>
<div class="form-group">
<label astr>home</label>
<input type="text" name="field3"class="form-control" required ng-minlength="5" ng-pattern="/^[-a-zA-Z0-9@\.+_]+$/" ng-model="ngObject.request.field3"/>
<my-ng-msg> </my-ng-msg>
</div>
因此,可以有许多字段具有类似的验证,但名称不同,您能帮助我如何动态发送名称并将其附加到我的指令中,以便我的自定义指令接受名称并处理该特定元素吗?
表单.field1.$错误
应将字段名作为字段名fieldname1、fieldname2。
一旦我有了这样的方法,我就可以动态地更改变量中的HTML。
TPLS
任何提示或帮助。