问题描述
我有自定义的角度指令:
I have custom angular directive:
<div class="input-group" name="name" ng-class="{ 'has-error has-feedback' : invalid }">
<span class="input-group-addon"><i class="fa fa-paw"></i> {{label}}</span>
<input type="text" class="form-control input-lg" ng-model="ngModel" ui-mask="99.99.9999" ui-mask-placeholder ui-mask-placeholder-char="-" model-view-value="true" placeholder="mm.dd.yyyy" ng-required="required" />
<span ng-show="invalid" class="form-control-feedback" aria-hidden="true"><i class="fa fa-paw"></i></span>
</div>
指令初始化代码:
.directive("smth", function($rootScope) {
var link = function(scope, element, attrs) {
scope.invalid = false;
scope.$watch("ngModel", function(value) {
if(scope.ngModel) {
scope.invalid = !$rootScope.timeStringValid(scope.ngModel); }
else {
scope.invalid = false;
}
});
};
return {
restrict: "E",
scope: {
name: "=name",
label: "=label",
ngModel: "=",
required: "=required"
},
link: link,
templateUrl: "smth.html"
};
})
指令在表格中的用法:
<form class="form-horizontal" name="smthForm">
<div class="row">...</div>
<smth label="'Birth date'" ng-model="data.birthdate" type="birthdate" required="true"></smth>
</form>
当指令输入无效时,其外观会按预期更改.但是,保存指令的表单对它的有效性状态一无所知,而且我不知道如何使它手动工作.另一方面,表单以某种方式知道何时输入为空并变为无效(必需"参数起作用).我尝试了几种基于$ setValidity("smth",!scope.invalid)的方法,但是失败了,基本上我无法理解在我的自定义指令中哪个确切的实体必须具有$ invalid字段才能对其进行更改.当内部指令无效字段为true时,我应该添加什么使表格变为无效?
When directive input is invalid, appearance of it changes as expected. However, the form that holds directive doesn't know anything about its validity state and I can't figure out how to make it work manually. On the other hand, form somehow knows when the input is empty and becames invalid ("required" param works).I tried several approaches based on $setValidity("smth", !scope.invalid), but failed, basically I can't understand what exact entity must have $invalid field in my custom directive to change it.What should I add for the form to become invalid when internal directive invalid field is true?
推荐答案
您可以使用ngModel
验证器:
.directive("smth", function($rootScope) {
var link = function(scope, element, attrs, ngModelCtrl) {
// Add custom validator
ngModelCtrl.$validators["timeString"] = function(modelValue) {
return !$rootScope.timeStringValid(modelValue);
}
};
return {
restrict: "E",
scope: {
name: "=name",
label: "=label",
ngModel: "=",
required: "=required"
},
// require ngModel controller
require: "ngModel",
link: link,
templateUrl: "smth.html"
};
});
这样,角度将包含对其$invalid
属性和$errors
(myForm.myFieldName.$errors.timeString
)的验证错误
This way angular will include the validation errors to its $invalid
property and the $errors
(myForm.myFieldName.$errors.timeString
)
这篇关于如何判断角形自定义指令无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!