簡體   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