如何在angular指令中编译新的element.attr()?

时间:2014-10-23 10:25:16

标签: javascript angularjs directive

我没有意识到,如何使工作成为新的属性。 $ compile适用于clone(),replaceWith()等,但是,例如,我想通过添加指令来隐藏任何dom元素:

.directive('hidden', function($compile) {
                return {
                    scope:{},
                    link: function(scope, element, attrs){
                        scope.shown = false;
                        element.attr('ng-show','shown');
                    }
                }
            });

2 个答案:

答案 0 :(得分:1)

如果这实际上仅用于显示和隐藏内容,请按@Max建议进行操作,但如果您在ng-show使用link函数中创建属性,则controller无效。

如果问题是针对更复杂场景的考试,您可以使用以下代码。

// as the compile works with contents string you need the get it.
$compile(element.parent().contents())(scope);

希望这会有所帮助。

答案 1 :(得分:0)

在您的情况下,该指令无用,因为它复制了ng-show/ng-hide行为。

  1. 直接在DOM元素上使用ng-hide/ng-show
  2. 使用自定义指令,但不要在里面使用ng-show。而不是尝试element.hide()element.show()