我有一组用于绘制 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/