GTHvidsten GTHvidsten - 3 months ago 134
AngularJS Question

lightGallery (jQuery plugin) in AngularJS

I'm trying to get the lightGallery jQuery plugin (http://sachinchoolur.github.io/lightGallery/index.html) to work with AngularJS.

I found some answers that suggested I needed a directive, so I created the following:

.directive('lightGallery', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
jQuery(element).lightGallery();
}
};
})


Then in my view I do this:

<ul lightGallery>
<li ng-repeat="photo in album.photos" data-src="{{photo.fullres}}">
<img ng-src="{{photo.thumbnail}}" />
</li>
</ul>


(I also tried with
<ul light-gallery>
)
When I run the page nothing happens when I click any of the thumbnails.
I can put an
alert()
in the link function, though, and that is displayed.

How can I get AngularJS to play along with jQuery and this plugin?

UPDATE:

After some debugging it seems that
jQuery(element).lightGallery()
is executed before the model is bound to the view.
So the question then is how I can get a directive to be called when everything is bound and not before.

Clr Clr
Answer

Call lightGallery once ng-repeat is finished rendering.
You can just modify the directive like this

.directive('lightgallery', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      if (scope.$last) {

        // ng-repeat is completed
        element.parent().lightGallery();
      }
    }
  };
});

HTML

<ul>
  <li lightgallery ng-repeat="photo in photos" data-src="{{photo.fullres}}">
    <img ng-src="{{photo.thumbnail}}" />
  </li>
</ul>

Here is the demo plnkr