Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery plugin and angular repeat

Given a jQuery plugin, what is the cleanest way to initialise it on a list of elements rendered by ng-repeat?

For example, i want to make a list of words draggable. In the controller i take the list from the API:

$scope.words = Words.get(...)

And in the view i iterate on them:

<article ng-controller="WordsCtrl">
    <div class="word" ng-repeat="word in words">
        {{word}}
    </div>
</article>

What is left is to run the plugin initialisation code, like in:

$(elem).children('.word').draggable()

But this needs to be run after every change in the scope. Where does this go?

like image 927
danza Avatar asked Nov 10 '22 16:11

danza


1 Answers

If you are using jQuery, you can create a simple jqDraggable directive that will call .draggable():

app.directive('jqDraggable', function () {
  return {
      restrict: 'A',
      link: function (scope, elm, attr) {
          elm.draggable();
      }
  };       
});

You would then do:

<article ng-controller="WordsCtrl">
    <div jq-draggable="true" class="word" ng-repeat="word in words">
        {{word}}
    </div>
</article>

This should also work when your $scope.words changes.

Here is a sample plunker:
http://plnkr.co/edit/ywWifeNPcTFYTYFMI2Of?p=preview

like image 155
marcoseu Avatar answered Nov 14 '22 21:11

marcoseu