AngularJS 指令:使用包含/编译链接集合中的对象

AngularJS Directive: link objects in collection with transclude/compile

本文关键字:集合 链接 对象 编译 指令 包含 AngularJS      更新时间:2023-09-26

我的一个页面需要加载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重复。Ng-repeat允许您将内容的交互与父级分开。最大的区别在于,该指令永远不应该进入 DOM。我只是想要一种分别向每个路径添加指令的方法。

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

需要做的就是在父指令中设置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>