[英]AngularJS : Change the element associated with directive using transclude
如何更改與對transclude()
的調用相關聯的元素?
在我的應用程序中,我從服務器動態加載了整個SVG文件並顯示它。 我需要將行為添加到加載的內容。
目前,我有這樣的事情:
<div svg-canvas="urlToSVGContent"></div>
這會在div中加載SVG標簽。 這很好用,但是如果我想向每個<path>
, <circle>
等添加ng-click怎么辦? ng-click
已經可以直接用於svg路徑,這只是以某種方式引用元素的問題。
我已經可以使用transclude來為每個路徑運行一次指令:
<div svg-canvas="urlToSVGContent">
<svg-each-path>
<!-- call transclude once per path found -->
</svg-each-path>
</div>
但是在svg-each-path內部,雖然我對每個元素都有單獨的作用域,但該指令的el
參數毫無意義。 或者它仍然指向父div或其他內容。
我想這樣做:
<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) {
})
})
}
}
我一直在尋找$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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.