我有自定义角度指令:
<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字段来更改它。 当内部指令无效字段为真时,我应该添加什么表格才能变为无效?
答案 0 :(得分:3)
您可以使用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"
};
});
这种方式angular会将验证错误包含在$invalid
属性和$errors
(myForm.myFieldName.$errors.timeString
)