3

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.

Geo Jacob
  • 5,909
  • 1
  • 36
  • 43
TheHvidsten
  • 4,028
  • 3
  • 29
  • 62

3 Answers3

11

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

Clr
  • 687
  • 7
  • 11
  • A follow up question. lightGallery documentation states that you can use the data-sub-html attribute to display captions for images. I added this attribute to the LI element, but nothing was displayed. I also tried adding a separate div (inside the LI) and referring to that instead, but that didn't work either. Any tips on how to use the captions when using AngularJS? – TheHvidsten May 15 '15 at 20:48
  • Caption works fine for me. I think your caption div doesn't have any style so it is hiding behind the image. Either you can use lightGallery default '.custom-html' class or you can apply css by yourself. here is the updated [plnkr](http://plnkr.co/edit/XqzhI1ZEmpcpQqdRIfjd?p=preview) – Clr May 16 '15 at 03:20
  • Ah, I was missing the .custom-html class. If I encapsulated my caption in a div with that class the captions works. The documentation might need updating as that says `
  • ` which is exactly what I had. – TheHvidsten May 16 '15 at 09:07
  • uh, isn't that instantiating multiple `lightgallery` widgets for each item? – Martin Shishkov Jun 10 '19 at 14:08