【问题标题】:AngularJS Directive: link objects in collection with transclude/compileAngularJS 指令:使用 transclude/compile 链接集合中的对象
【发布时间】:2013-11-24 20:30:49
【问题描述】:

我的一个页面需要加载一个 SVG 文件然后对其进行编辑。现在,它是一个巨大的指令,它处理整个 SVG 以及与形状相关的每个交互。我想将其拆分,以便可以将形状的交互放入单独的指令中。

这是我现在所做的:

<svg-canvas 
    fills="fills"
    src="{{svgImageUrl}} 
    selected-shape="selectedShape"
    on-drop-fill="addFill(pathId, fill)"
/>

该指令同时管理父图形(SVG)和每个子图形的交互。例如,我为每个形状添加了一个单击处理程序,并更新了范围上的选定形状。我深入观察填充物的变化,查找正确的形状并应用它。

我宁愿做这样的事情:

<svg-canvas src="{{svgImageUrl}}>
    <svg-each-shape as="shape" svg-click="selectShape(shape)" svg-fill="fills[shape.id]" on-drop-fill="addFill(shape, fill)"/>
</svg-canvas>

从概念上讲,能够为 svg-click、svg-fill 等创建单独的指令似乎更简洁。如果你眯着眼睛,这很像 ng-repeat。 Ng-repeat 允许您将内容的交互与父级分开。最大的不同是该指令永远不应该进入 DOM。我只是想要一种方法来分别向每个路径添加指令。

是否可以使用嵌入将集合中的对象(形状)链接到子范围,以便我可以使用它?不把它放在 DOM 中?如何?

【问题讨论】:

  • 不放到DOM中是什么意思?
  • 页面上不应有 元素。 svg-canvas 将整个 SVG 内容转储到页面中。我想使用该内部指令作为向每个内部形状/路径添加指令的启动点,但是在将 SVG dom 添加到页面后,我通过遍历 SVG dom 来获得这些指令。 引用了每个形状对象,但我的控制器没有。我想使用 将两者联系在一起。
  • 简单的演示可能会有所帮助

标签: javascript angularjs svg angularjs-directive


【解决方案1】:

您需要做的就是在父级中设置transclude: true,并为每个子级调用一次transclude 函数,并在范围上设置适当的属性,以便子指令可以使用。

这是一个简化的例子:svgCanvas.js

.directive('svgCanvas', function() {
    return {
        restrict: 'AE', 
        transclude: true,
        compile: function(tElement, tAttrs, transclude) {
            return function(scope, el, attrs) {
                return link(scope, el, attrs, transclude)
            }
        }
    }

    function link(scope, el, attrs, transclude) {
         // ... other code
         // after loaded 
         function afterLoaded() {
             el.find("rect, path").each(function() {
                 var childScope = scope.$new()
                 // child directives can read ._path to work their magic
                 childScope._path = $(this)
                 transclude(childScope, function(clone) {
                    // You don't have to do anything in here if you don't want
                    // transclude runs all child directives
                 })
             })
         }

    }
})

这是一个内部指令的示例:svgClick.js

.directive('svgClick', function() {
    return {
        restrict: 'A',
        link: function(scope, el, attrs) {
            var $path = scope._path
            $path.click(function() {
                scope.$apply(function() {
                    scope.$eval(attrs.svgClick)
                })
            })
        }
    }
})

这就是你将如何使用它

<svg-canvas src="{{svgImageUrl}}">

    <svg-each-path
        svg-click="selectPath(path.id)" 
    />

</svg-canvas>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    相关资源
    最近更新 更多