SVG的角度替换指令(结果在DOM中,但未显示)



我有一组用于绘制svg图表的Angular指令,我需要使用这些指令。确切的指令名称取决于图表的类型(如"barlineChart"、"bulletChart"等)。为了简化操作而不是复制粘贴,我决定创建一个"wrapper"指令,让您可以选择图表类型。

如果使用原始指令,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时,您可能需要使用指令的pre-link函数(甚至可能是编译函数),angular需要注意新元素(即:注入的元素包含angular代码)。

请参阅https://code.angularjs.org/1.2.16/docs/api/ng/service/$compile

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

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

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

最新更新