简体   繁体   中英

How to Set Angular Directive to the DOM element created in Javascript

I have a directive which allows the drag drop of Dom elements that is :

JS:

  angular.module('animationApp').directive('myDraggable', ['$document', function($document){return{link: function(scope, element, attr) {
  var startX = 0, startY = 0, x = 0, y = 0;
  console.log("In myDraggable directive code");
  element.css({
   position: 'relative',
   cursor: 'pointer'
  });
  element.on('mousedown', function(event) {
    // Prevent default dragging of selected content
    event.preventDefault();
    startX = event.pageX - x;
    startY = event.pageY - y;
    $document.on('mousemove', mousemove);
    $document.on('mouseup', mouseup);
  });
  function mousemove(event) {
    y = event.pageY - startY;
    x = event.pageX - startX;
    element.css({
      top: y + 'px',
      left:  x + 'px'
    });
  }
  function mouseup() {
    $document.off('mousemove', mousemove);
    $document.off('mouseup', mouseup);
  }
}};}]);

Now , I can use it and is working perfectly fine (Drag/Drop functionality) when i create a DOM element at HTML page and assign the specific directive . Like ,

HTML:

<div my-draggable = "">Hello</div>
<div my-draggable = "">Sid</div>

The issue is , I'm unable to assign the directive to those elements I'm creating in Javascript Code . Like,

JS:

var tempView = document.getElementById('ngView');
var div = document.createElement("div");
var t = document.createTextNode("This is a paragraph.");
div.appendChild(t);
div.setAttribute("my-draggable","");
tempView.appendChild(div);

The Directive isn't working in this Case !

What is the problem ?

What did i do wrong ?

Thanks!

You need to $compile the element you are creating, before appending it to the DOM:

div.setAttribute("my-draggable","");
$compile(div)($scope)
tempView.appendChild(div);

There's an answer to a similar question here .

You can not add directive as a HTML node only. Because in this way, you are mixing jquery/javascript with AngularJS. When you add a new element, AngularJS has no way of knowing that it has been added. You can use $compile service to compile your HTML element so that AngularJS actually exectutes your directive.

See this: Dynamically add directive in AngularJS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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