javascript - 将 AngularJS 指令绑定(bind)到元素

标签 javascript angularjs raphael

我创建了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);
  },
 };
});

http://jsfiddle.net/nnfve2tx/5/

关于javascript - 将 AngularJS 指令绑定(bind)到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27479591/

相关文章:

javascript - 如何使用 If 语句来确认整数已放入 javascript 的文本字段中?

javascript - Angular : Correct way to send parameters to directive

angularjs - 如何在启用行选择的 Angular ui 网格中启用文本选择

javascript - Snap.svg 沿路径拖动组

javascript - 区分具有相同类、id和父类的表行

javascript - 在子链接页面上时触发父链接的事件类

angularjs - 如何使用 Angular orderBy 过滤器按字母顺序对字符串数组进行排序?

javascript - 在文件1中使用文件2时,在文件2中使用文件1中定义的javascript变量

javascript - jQuery SVG 与 Raphael

.net - javascript 和 SQL 之间的共享规则