首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >AngularJS :使用transclude更改与指令关联的元素

AngularJS :使用transclude更改与指令关联的元素
EN

Stack Overflow用户
提问于 2014-02-10 15:33:26
回答 1查看 225关注 0票数 0

如何更改与调用transclude()关联的元素

在我的应用程序中,我从服务器动态加载整个SVG文件并显示它。我需要将行为添加到加载的内容中。

目前,我有这样的事情:

代码语言:javascript
运行
复制
<div svg-canvas="urlToSVGContent"></div>

这将在div中加载一个SVG标记。这很好,但是如果我想向每个<path><circle>等添加ng单击怎么办?ng-click已经可以在svg路径上开箱即用,这只是一个引用元素的问题。

我已经可以使用transclude创建一个指令,它将对每个路径运行一次:

代码语言:javascript
运行
复制
<div svg-canvas="urlToSVGContent">
    <svg-each-path>
        <!-- call transclude once per path found -->
    </svg-each-path>
</div>

但是在svg-每条路径中,虽然我为每个元素都有一个单独的作用域,但是指令的el参数是没有意义的。或者它仍然指向父级或什么的。

我想这样做:

代码语言:javascript
运行
复制
<div svg-canvas="urlToSVGContent">
    <svg-each-path ng-click="onPathClick()">
    </svg-each-path>
</div>

这就是svg-each-path当前的样子:

代码语言:javascript
运行
复制
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) {

            })
        })
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-10 16:38:17

我在找$compile服务。它允许您接受任何html字符串或元素,并将其绑定到一个作用域以运行指令。根本不需要翻译。

代码语言:javascript
运行
复制
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)
        })
    }
}

用法:

代码语言:javascript
运行
复制
<div svg-canvas="urlToSVGContent">
    <svg-each-path ng-click="onPathClick(...)">
    </svg-each-path>
</div>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21681342

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档