如何更改与调用transclude()关联的元素
在我的应用程序中,我从服务器动态加载整个SVG文件并显示它。我需要将行为添加到加载的内容中。
目前,我有这样的事情:
<div svg-canvas="urlToSVGContent"></div>这将在div中加载一个SVG标记。这很好,但是如果我想向每个<path>、<circle>等添加ng单击怎么办?ng-click已经可以在svg路径上开箱即用,这只是一个引用元素的问题。
我已经可以使用transclude创建一个指令,它将对每个路径运行一次:
<div svg-canvas="urlToSVGContent">
<svg-each-path>
<!-- call transclude once per path found -->
</svg-each-path>
</div>但是在svg-每条路径中,虽然我为每个元素都有一个单独的作用域,但是指令的el参数是没有意义的。或者它仍然指向父级或什么的。
我想这样做:
<div svg-canvas="urlToSVGContent">
<svg-each-path ng-click="onPathClick()">
</svg-each-path>
</div>这就是svg-each-path当前的样子:
function svgEachPath() {
return {
restrict: 'E',
transclude: 'element',
priority: 1000,
terminal: true,
link: link,
}
function link(scope, el, attrs, ctrl, $transclude) {
// scope.paths was set by the svg-canvas directive
scope.paths.forEach(function(path) {
var childScope = <InnerScope> scope.$new()
childScope.path = path
// how can I change "el" to point to path?
// or get the clone to be a clone of the path instead of the parent element?
$transclude(childScope, function(clone) {
})
})
}
}发布于 2014-02-10 16:38:17
我在找$compile服务。它允许您接受任何html字符串或元素,并将其绑定到一个作用域以运行指令。根本不需要翻译。
function svgEachPath($compile) {
return {
restrict: 'E',
// should stop processing directives. we don't want ng-click to apply to the fake element
terminal: true,
priority: 1000,
link: link,
}
function link(scope, el, attrs) {
scope.paths.forEach(function(path) {
// copy in all my attributes to the element itself
Object.keys(attrs)
.filter((key) => key[0] != "$")
.forEach((key) => {
// use snake case name, not camel case
path.attr(attrs.$attr[key], attrs[key])
})
// "compile" the element - attaching directives, etc
var link = $compile(path)
link(scope)
})
}
}用法:
<div svg-canvas="urlToSVGContent">
<svg-each-path ng-click="onPathClick(...)">
</svg-each-path>
</div>https://stackoverflow.com/questions/21681342
复制相似问题