[英]AngularJS Directive: link objects in collection with transclude/compile
我的一個頁面需要加載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中。 我只是想要一種方法來分別向每個路徑添加指令。
是否可以使用transclusion將集合中的對象(形狀)鏈接到子范圍,以便我可以使用它? 沒有把它放在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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.