繁体   English   中英

将AngularJS指令绑定到元素

[英]Binding AngularJS directive to element

我已经使用javaScript在dom上创建了SVG图像。 现在我想在这些图像上绑定指令,我不确定该怎么做。 谁能帮助我找到解决方案?
谢谢。
我在这里写我的代码:
我想将此forImage指令添加到图像元素。 简而言之,我只想知道,如果我使用javaScriptDOM上创建元素,而不是如何使用Angular directive.在其上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");
            });
        }
    }
});

好的,我认为这终于是解决方案。 看看小提琴。 我添加了一个红色矩形,以便您可以看到,您的指令仅在图像上触发。 我使用$ 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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM