【发布时间】:2015-05-14 21:55:44
【问题描述】:
所以,这有点复杂。
我有一个指令可以根据某些标准加载 SVG 文件。这是一个很大的指令,所以我不会在这里发布它,因为它不会影响我的问题,你只需要知道它存在。 在该指令中,我有一个包含以下 HTML 的模板文件:
<div ng-include="svgPath" onload="loaded()"></div>
注意 onload 功能。这在 SVG 加载时调用。
在这个 SVG 内部,有一些我需要与之交互的隐藏组。因为这改变了 DOM,所以我编写了另一个指令,如下所示:
.directive('kdGraphicsRepeater', function () {
return {
restrict: 'A',
scope: {
targetElementId: '@kdGraphicsRepeater'
},
templateUrl: '/assets/tpl/directives/graphicsRepeater.tpl.html',
link: function (scope, element) {
// Declare our options
scope.options = [];
// Get our target elements
var target = angular.element(document.getElementById(scope.targetElementId)),
svg = angular.element(target.find('svg')),
children = svg.children();
console.log(target.length);
console.log(svg.length);
console.log(children.length);
// Loop through the SVG children
for(var i = 0; i < children; i++) {
// Get the current child
var child = children[i],
childId = child.attr('id');
console.log(childId);
// If we have an option
if (childId && childId.indexOf('options-') > -1) {
// Push the name to our options array
scope.options.push(childId.replace('options-'));
}
}
}
}
})
对应的模板如下:
<div ng-repeat="item in options">
{{ item }}
</div>
正如你应该能够理解的那样。我正在尝试遍历 SVG 直接子级并检查是否有任何元素与 options- 有部分 id 匹配。如果有,我将它们(省略“options-”字符串)添加到 scope.options 变量中。我的模板只是循环显示它们。
问题是 SVG 没有为此指令加载,因此 console.log(svg.length) 返回 0。我需要某种方式知道 SVG 何时加载。 有人可以帮帮我吗?
【问题讨论】:
-
如何为代表那些“选项”的 SVG 元素定义一个指令?这些将与主要父指令具有共享范围,因此他们可以轻松地通知它他们存在。
-
我猜你的指令是在加载 svg 之前被调用的?
-
@Sergiu SVG 是从我无法控制的文件中加载的。
-
@ssayyed 是的,这似乎是问题所在。我希望它等到 SVG 加载后再加载自身。
-
但是没有什么能阻止你定义一个
circle指令,该指令在所说的 SVG 内的每个<circle>上运行。 - 我的意思是您不需要更改 SVG 标记。
标签: javascript angularjs svg