angularjs - 如何在另一个指令中调用一个指令

标签 angularjs angularjs-directive compilation

这是我在 StackOverflow 中的第一个问题。

我正在使用 AngularJS,我正在创建可重用的 boundingBox、Resizable 和 Draggable 指令。

BoundingBox 指令的想法是它应该将 Draggable 和 Resizable 指令附加到 SAME DOM 元素(如果它们还没有的话)。

angular.module('WYSIRWYG.BoundingBox', [])
.directive('boundingBox', [function() {

return {
    restrict: 'A',
    transclude: false,
    priority: -1000,

    compile: function($element, $attrs) {

        console.log($element.html());
        return {
            pre: function($scope, $element, $attrs) {

            },

            post: function($scope, $element) {
                $element
                .resizable({
                    handles: $attrs.bbHandles
                });
            }
        };
    }
};
}]);

对于可拖动指令:

angular.module('WYSIRWYG.Draggable', [])
.directive('draggable', [function() {

return {
    restrict: 'A',
    transclude: false,
    priority: -1000,

    compile: function($element, $attrs) {

        return {
            pre: function($scope, $element, $attrs) {

            },

            post: function($scope, $element) {
                $element
                .draggable({
                    delay: $attrs.dragDelay
                });
            }
        };
    }
};
}]);

和 DOM:

<div bounding-box bb-handles="n, e, s, w, ne, se, sw, nw" style="background:red; width: 100px; height: 100px; display: block; position: absolute; top: 50px; left: 100px;">div content</div>

请注意,我没有向 div 添加 Resizable 或 Draggable 属性指令,所以我希望 BoundingBox 这样做。

问题是我不知道如何让 AngularJS 将这个指令附加到当前的 DOM 元素。 我试过 $compile 但它给出了无限循环,因为 angular 试图一次又一次地编译 BoundingBox ...

最佳答案

一个解决方案确实是在你的 boundingBox 中使用 $compile 但只有在你删除了 bounding-box 属性之后它才不会' t 触发一个循环。

element.removeAttribute('bouding-box');
element.setAttribute('draggable');
$compile(element)(scope);

关于angularjs - 如何在另一个指令中调用一个指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29809443/

相关文章:

javascript - Angular 指令中的 Transclude 将元素放入单个 'span'

java - 为什么 Java 类的编译与空行不同?

javascript - 垂直 ionic 滚动未正确实现为页脚按钮覆盖列表组件

javascript - 如何将 ng-bind 设置为从 Angular http 返回的值?

javascript - 如何找到特定的 html 元素,AngularJS, Protractor

angularjs - {{::photo.src}} 的一次性绑定(bind)抛出错误

javascript - 监视指令属性

javascript - ng-repeat 中的 Angular 自动触发特定指令

java - GWT 语言环境属性 - 用户的新语言需要更多编译

compilation - 从三地址代码到 JVM 字节码的代码生成