1

I have a problem doing this with angular:

http://jsfiddle.net/EpxHE/14/light/

This is what I made:

Directive:

.directive("myDirective", function () {
        return {
            restrict: "A",
            replace: true,
            compile: function (element, attrs) {
                var $newDiv = $("<div class='dragdiv'>4</div>");
                makeElementAsDragAndDrop($newDiv);
                element.html($newDiv);
            }
        }

    })

function makeElementAsDragAndDrop(elem) {
    $(elem).draggable({
        snap: '#droppable',
        snapMode: 'outer',
        revert: "invalid",
        cursor: "move",
        helper: "clone"
    });
    $(elem).droppable({
        drop: function(event, ui) {
            var $dragElem = $(ui.draggable).clone().replaceAll(this);
            $(this).replaceAll(ui.draggable);
            makeElementAsDragAndDrop(this);
            makeElementAsDragAndDrop($dragElem);
        }
    });
}

HTML:

<div my-directive ng-repeat="item in items"></div>

I think the problem is because the makeElementAsDragAndDrop() function is call only once and before the element is created. Do you have a solution ? Thanks

1 Answer 1

4

I did something very similar to what you're trying to do. However, instead of in my directive's compile function, I instead attach the jquery ui widget to the directive element inside my link function, like so:

app.directive('sortable', function() {
  return {
    restrict: 'A',
    link: function(scope, elt, attrs) {
      return elt.sortable({
        revert: true,
        stop: function(evt, ui) {
          return scope.$apply(function() {
            /* code goes here */
          });
        }
      });
    }
  };
});

Notice that immediately after defining the stop event on my sortable widget, I call scope.$apply. Misko Hevery has described that as getting back into the Angular execution context.

I found out how to do this from Ben Farrell's blog post.

You can also see how I did it, posted here in my GithHub repo.

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

2 Comments

Remember $scope.apply!!! Omitting this simple call blocked my progress for a couple of days.
Excellent - thanks! In case it helps others, I was having a hard time getting this to work until I realised that the ng-repeat affects the scope: from the docs, it instantiates a template with a new scope once per item. So any changes you make to scope in the link function will only be visible inside the ng-repeat.

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.