我创建了SVG
dom 上的图像使用 javaScript
。现在我想在这些图像上绑定(bind)指令。我不知道该怎么做。谁能帮我找到解决方案?
谢谢。
我在这里写我的代码:
我想将此 forImage 指令添加到图像元素。简而言之,我只想知道如果我在 DOM
上创建一个元素使用javaScript
,比如何bind
使用Angular directive.
对其进行事件
更新:我发现$compile用于动态添加指令。有没有办法从 cntroller 编译 DOM?
//HTML
<body ng-controller= "Ctrl" >
<div class="row">
<div id="editor"></div>
</div>
</body>
//My controller
app.controller('Ctrl', function ($scope) {
var paper = Raphael("editor", 635,500);// Raphael element(it creates SVG tag) to draw image.
var image = paper.image(img.src, 200, 200,300,400);// Image drawn on the SVG.
})
//My directive
app.directive('forImage', function () {
return {
restrict:'CA',
link: function (scope,elem,attr) {
elem.bind('mousedown', function (e) { // Mousedown event to be bind on image
console.log("Image binding");
});
}
}
});
最佳答案
好吧,我想这终于是解决方案了。看看 fiddle 。
我添加了一个红色矩形,以便您可以看到,您的指令仅在图像上触发。
我使用 $compile 来使添加的指令 (setAttribute()
) 工作。
app.directive('raphaelDir', function($compile) {
return {
restrict: 'E',
replace: 'true',
template: '<div id="editor"></div>',
link : function(scope,element, attrs) {
var paper = Raphael("editor", 500,500);
var image = paper.image(
"http://i.forbesimg.com/media/lists/companies/google_416x416.jpg",
20,30,100,100);
image.node.setAttribute('for-image', '');
$compile(element)(scope);
},
};
});
关于javascript - 将 AngularJS 指令绑定(bind)到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27479591/