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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With