如何编写Angular指令以基于表单验证更新CSS类
我有以下Angular/HTML,它使用引导CSS类来指示表单是否使用Angular验证有效如何编写Angular指令以基于表单验证更新CSS类,css,angularjs,Css,Angularjs,我有以下Angular/HTML,它使用引导CSS类来指示表单是否使用Angular验证有效 <form name="editor" novalidate> <div class="form-group" ng-class="{'has-error': editor.name.$dirty && (editor.name.$error.invalid || editor.name.$error.required)}"> <
<form name="editor" novalidate>
<div class="form-group" ng-class="{'has-error': editor.name.$dirty && (editor.name.$error.invalid || editor.name.$error.required)}">
<input type="text" class="form-control" name="name" maxlength="150" data-ng-model="name" required />
</div>
</form>
我有以下指令外壳,但我不知道如何监视编辑器.name
(或输入
属性)以更新类
myApp.directive("formGroup", function () {
return {
restrict: "A",
scope: {
input: "@"
},
replace: false,
link: function (scope, elem, attrs) {
}
};
});
我假设我需要将相关代码放入link函数中,可能还需要使用$watch
,但除此之外,我还有些茫然您应该使用属性来执行此操作:
myApp.directive("formGroupElement", function () {
return {
restrict: "A",
require: "ngModel"
scope: {
input: "@"
},
replace: false,
link: function (scope, elem, attrs, ngModelController) {
//ngModelController.$setValidity();
}
};
});
或:
我的结论如下:
myApp.directive("formGroup", function ($parse) {
return {
restrict: "A",
scope: {
input: "@"
},
replace: false,
require: "^form",
link: function (scope, elem, attrs, ctrl) {
var expression = [ctrl.$name, scope.input, "$invalid"].join(".");
scope.$parent.$watch(expression, function (val) {
alert(expression + " " + val); // Pops the value.
});
}
};
});
请注意,尽管HTML中的表达式是editor.name.$error.invalid
,但在链接函数中它是editor.name.$invalid
使用表单控制器意味着我不必在
上设置ng模型属性。如果我是你,我会启动一个plunker,并尝试自己编写代码。如果你被困住了,回到这里,把那辆车连起来。我确实认为您的指令范围需要是“=”而不是@,并且您不需要$watch,因为您要查看的值将已经绑定到视图模板中(以hte输入字段的形式)。但是你自己试试看,这是最好的学习方法。试一下!这就是我为什么要在这里发帖的原因。那么,你能链接一下plunker吗?我可能误解了你的答案,但我不想在指令中实际设置有效性。我只想根据已经完成的验证更新div的CSS类。我想我真正需要的答案是如何在directive link函数中获得editor.name.$error
对象?
myApp.directive("formGroup", function () {
return {
restrict: "A",
require: "ngForm"
scope: {
input: "@"
},
replace: false,
link: function (scope, elem, attrs, ngFormController) {
//ngFormController.$setValidity();
}
};
});
myApp.directive("formGroup", function ($parse) {
return {
restrict: "A",
scope: {
input: "@"
},
replace: false,
require: "^form",
link: function (scope, elem, attrs, ctrl) {
var expression = [ctrl.$name, scope.input, "$invalid"].join(".");
scope.$parent.$watch(expression, function (val) {
alert(expression + " " + val); // Pops the value.
});
}
};
});