我正在对指令进行验证,强制用户选中该复选框。如果未标记复选框,则会显示错误消息。我的问题是消息转移到复选框的文本。
我最后需要验证消息。我需要在指令中执行此操作,我不想触摸控制器或模板。 怎么办?
app.directive('validate', function ($timeout) {
return {
restrict: 'AE',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
if (!ngModel){
return;
}
ngModel.$setValidity('validation', false);
scope.directive_function= function(){
alert("directive function");
}
ngModel.$parsers.push(function(val){
if(val==true){
ngModel.$setValidity('validation', true);
var elemento_eliminar=(angular.element((document.getElementById('errorchec' ))));
elemento_eliminar.remove();
}else{
ngModel.$setValidity('validation', false);
var newDirective = angular.element('<div id="errorchec" class="span_wrong" style="margin-top:5px; color:red">'+"must be required"+'</div>');
element.after(newDirective);
}
})
}
};
});
答案 0 :(得分:1)
您只需添加position:absolute
css属性即可对齐验证
<div id="errorchec" class="span_wrong"
style="position: absolute;margin-top:5px;color:red;">must be required</div>
答案 1 :(得分:0)
要使其显示在输入元素旁边,请将display: inline-block
添加到div
元素,或者只使用span
。
<div id="errorchec" class="span_wrong"
style="margin-top:5px; color:red; display: inline-block;">
答案 2 :(得分:0)
<label><input type="checkbox" ng-model="check1" value='value1' validate />value1</label>
您的HTML中有一个<label>
,其中包含<input>
和一些文本value1
。 input
是指令引用的元素;该指令正确地将错误<div>
放在input
之后,但在文本之前。
相反,您实际上希望错误在<label>
之外。为此,请参考元素的.parent
。
element.parent().after(newDirective);