3

I'm using a jQuery UI Sortable element inside an AngularJS directive (initialized with .sortable() in the linking function). The problem is that the sortable does work only after the first click on the element...

I have tried to use .trigger('click') on the element but it doesn't work too. If I initialize the sortable outside of angular (in document.ready()) it works fine.

Any ideas to debug this problem ?

2
  • 1
    if I use setTimeout to initialize the sortable it works... Commented May 20, 2013 at 10:15
  • setTimeout (of 0ms) worked for me too, although apparently this works in jQuery 1.x: github.com/angular-ui/ui-sortable/issues/2 Commented May 30, 2013 at 11:17

1 Answer 1

1

You need to make sure the DOM is ready inside your Angular directive. I think something like this would work:

<ul>
  <li ng-repeat="item in items" my-sortable="true">{{item.title}}</li>
</ul>


angular.module('myApp',[]).directive('mySortable', function() {
   return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        element.ready(function() {
           // Initialize UI Sortable
        });
      }
   };
});

This will not work for dynamically loaded lists. The problem is you need to make sure the list is fully rendered before initializing the sortable. So my suggestion is for the directive to check if the last element in the list is ready (scope.$last):

 angular.module('myApp',[]).directive('mySortable', function() {
   return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        if (scope.$last=== true) {
          element.ready(function () {
              // Initialize UI Sortable
              element.parent().sortable();
           });
         }
      }
   };
});
Sign up to request clarification or add additional context in comments.

2 Comments

thank you Andre, it works, but when I add other sortables (they are generated by ng-repeat) it has the same behavior, no drag on first click...
Please see my revised answer

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.