javascript - SVG 的 Angular 替换指令(结果位于 DOM 中但未显示)

标签 javascript jquery angularjs svg angularjs-directive

我有一组用于绘制 svg 图表的 Angular 指令,我需要使用它们。确切的指令名称取决于图表的类型(即“barlineChart”、“bulletChart”等)。为了简化事情而不是复制粘贴,我决定创建一个“包装器”指令,让您选择图表类型。

如果使用原始指令,html 看起来如下:

<g x-barline-chart
   x-chart-properties="{{component1.properties}}"></g>
<g x-bullet-chart
   x-chart-properties="{{component2.properties}}"></g>

使用我的新指令:

<g x-ng-repeat="component in chart.components"
   x-chart-type="{{component.chartType}}"
   x-chart-properties="{{component.properties}}"></g>

指令代码:

.directive('chartType', ['$compile', function($compile) {
    return {
        scope: {
            type : '@chartType'
        },
        link: function (scope, element, attributes) {
            attributes.$set(scope.type, "");
            $compile(element.contents())(scope);
        }
    }
}]);

问题就在这里。新元素被编译,如果我检查 DOM,我可以看到它已经添加了新属性。但是,它没有呈现,并且似乎没有使用我刚刚附加的新指令。

我做错了什么?

最佳答案

我认为当您修改 DOM 时,您可能需要使用指令的预链接功能(甚至可能是编译功能),并且 Angular 需要了解新元素(即:注入(inject)的元素包含 Angular 代码) .

参见https://code.angularjs.org/1.2.16/docs/api/ng/service/ $编译

要将其更改为预链接,请执行以下操作:

.directive('chartType', ['$compile', function($compile) {
    return {
        scope: {
            type : '@chartType'
        },
        link: {
            pre : function (scope, element, attributes) {
                attributes.$set(scope.type, "");
                $compile(element.contents())(scope);
            }
        }
    }
}]);

如果这不起作用,那么您可能需要使用编译函数。但我过去曾经做过这种指令,并且从来不需要使用编译函数,预链接对于我的情况来说是可以的。

关于javascript - SVG 的 Angular 替换指令(结果位于 DOM 中但未显示),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23138090/

相关文章:

angularjs - 如何在自定义指令中获取 ng-model 值

javascript - 合并有分歧的数组

javascript - 如何编写 onclick 函数以防止冒泡

jquery - 带有 blueimp jquery 文件上传的自定义文件上传按钮

javascript - 带按钮的简单 Jquery slider

javascript - fullcalendar 上的安装错误

javascript - 当新视频加载 Tauri 和 Svelte 时如何更新视频的当前时间?

javascript - 在 HTML map 的特定位置添加叠加层

angularjs - Angular UI/select2 multiple 如何预选值/选项?

javascript - Angular JS ng-repeat 不显示选项