我有以下 Angular/HTML,它使用 Bootstrap 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)}">
<input type="text" class="form-control" name="name" maxlength="150" data-ng-model="name" required />
</div>
</form>
div.form-group
不止一个,显然代码重复很多。我想做的是创建一个 Angular 属性指令,如果其中包含的输入无效,它将更新 div.form-group
元素的类。
这是我想要获得的标记:
<div class="form-group" data-form-group data-input="editor.name">
...
</div>
我有以下指令外壳,但我不知道如何监控 editor.name
(或 input
属性)以更新类。
myApp.directive("formGroup", function () {
return {
restrict: "A",
scope: {
input: "@"
},
replace: false,
link: function (scope, elem, attrs) {
}
};
});
我假设我需要将相关代码放在链接函数中,并且可能使用 $watch
但除此之外我有点一头雾水
最佳答案
你应该使用ngModelController这样做的属性:
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 () {
return {
restrict: "A",
require: "ngForm"
scope: {
input: "@"
},
replace: false,
link: function (scope, elem, attrs, ngFormController) {
//ngFormController.$setValidity();
}
};
});
关于css - 如何编写 Angular 指令以基于表单验证更新 CSS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35153198/