css - 如何编写 Angular 指令以基于表单验证更新 CSS 类

标签 css angularjs

我有以下 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();
       }
   };
});

ngFormController :

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/

相关文章:

angularjs - 如何在没有 ng-repeat 的情况下在 Angularjs 中实现 "Load more"分页?

css - 到达固定元素的末尾时防止滚动非固定元素

javascript - 如何从范围对象中获取所需的数字位数?

html - 彼此相邻的 div,1 : 200px, 2:100%

javascript - 如何让 jQuery 只选择第一个 closest() 元素?

javascript - Angular Material 设计 : $mdMedia ('gt-md' ) not working in html

angularjs - 在 PHPMailer 中处理 AngularJS 数组

javascript - 如何获取for循环 Angular js中的所有值

css - 如何正确对齐表格中的图标和文本?

javascript - 以 Angular 动态地将元素添加到DOM