草庐IT

javascript - Angular Directive(指令) : Adding ng-class directive at compile time on existing template element

coder 2025-02-27 原文

长话短说,这个想法是通过不必手动添加 ng-class={'has-error': 'formName.inputName.$invalid'} 来简化模板每一个form-group

所以我想创建一个指令来生成一个字符串,该字符串将被添加到模板元素中。该字符串是一个带有表达式的 ng-class 属性

我认为创建一个在编译阶段添加 ng-class 属性的快速指令就足够了,但它似乎并没有削减它。

指令定义对象

{
    restrict: 'C',
    compile: function(tElement, tAttrs) {
        var $elem = angular.element(tElement),
            formName = $elem.parents('[ng-form]').length ? $elem.parents('[ng-form]').attr('ng-form') : $elem.parents('form').attr('name'),
            controlName = $elem.find('.form-control').attr('name');

        $elem.attr('ng-class', '{"has-error": ' + formName + '.' + controlName + '.$invalid}');

        console.log('added ng-class attr', $elem.attr('ng-class'));
    }
}

Plunk here

查看控制台

The 1st form-group has its ng-class attribute added dynamically.
The expression associated with it is correct
But the ng-class directive is never executed

The 2nd form-group has its ng-class attribute added manually in the template and works as expected, obvisouly

--

我在这里错过了什么?

最佳答案

设法在不添加额外观察者的情况下使其工作(当然,ng-class 使用观察者,但在测试建议的解决方案后,我发现观察者数量有所增加)

我不得不在 postLink 中 $compile 新的 DOM 元素,但为了避免递归,我需要删除指令本身。这阻止了我重复使用类名,例如“form-group”

这是工作指令

function bsFormClass($compile) {
  return {
    restrict: 'A',

    compile: function (tElement) {

        var $elem = angular.element(tElement),
            controlName = $elem.find('.form-control').attr('name');

        if(!controlName) { return; }

        var formName = $elem.parents('[ng-form]').length ? $elem.parents('[ng-form]').attr('ng-form') : $elem.parents('form').attr('name');

        $elem.attr('ng-class', '{"has-error": ' + formName + '.' + controlName + '.$invalid}');
        $elem.removeAttr('bs-form-class');

        return {
            post: function(scope, elem, attrs) {
                $compile(elem)(scope);
            }
        }
    }
  }
}

谢谢大家的帮助

关于javascript - Angular Directive(指令) : Adding ng-class directive at compile time on existing template element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34076232/

有关javascript - Angular Directive(指令) : Adding ng-class directive at compile time on existing template element的更多相关文章

随机推荐