2

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!

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.