AngularJS 中的 lightGallery(jQuery 插件)

lightGallery (jQuery plugin) in AngularJS

我正在尝试让 lightGallery jQuery 插件 (http://sachinchoolur.github.io/lightGallery/index.html) 与 AngularJS.

一起使用

我发现一些答案表明我需要一个指令,所以我创建了以下内容:

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

然后在我看来我这样做:

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

(我也试过 <ul light-gallery>) 当我 运行 页面单击任何缩略图时没有任何反应。 不过,我可以在 link 函数中放置一个 alert(),然后显示出来。

如何让 AngularJS 与 jQuery 和这个插件一起玩?

更新:

经过一些调试后,似乎 jQuery(element).lightGallery() 在模型绑定到视图之前执行。 所以接下来的问题是我如何才能在所有内容都绑定时而不是之前获得要调用的指令。

ng-repeat 完成渲染后调用 lightGallery。
您可以像这样修改指令

.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>

这是演示plnkr

没有指令..

HTML

<ul id="lightgallery">
  <li ng-repeat="image in album.images" data-src="{{imagem.fullres}}">
    <img ng-src="{{image.thumbnail}}" />
  </li>
</ul>

JavaScript

// $http, Restangular whatever to return data in album.images

// unbind before..
jQuery('#lightgallery').unbind().removeData();

// $timeout after
$timeout(function () {
  jQuery('#lightgallery').lightGallery();
}, 100);

适合我..

结合使用 2 个指令,您可以通过一个指令指定一个父级,以及将选项传递给一个作用域变量,这提供了对 Light Gallery 进行更多自定义的机会。二级指令触发父级绑定(使用@Clr 解决方案中提出的相同想法)

此指令用于父元素,您可以传递一个 galleryOptions 范围变量,该变量在绑定 Light Gallery 时简单地传递:

.directive('lightGallery', function() {
    return {
        restrict: 'A',
        scope: {
            galleryOptions: '='
        },
        controller: function($scope) {

            this.initGallery = function() {
                $scope.elem.lightGallery($scope.galleryOptions);
            };

        },
        link: function(scope, element, attr) {
            scope.elem = element;
        }
    }
})

此指令适用于 Light Gallery 中的每个 "item":

.directive('lightGalleryItem', function() {
    return {
        restrict: 'A',
        require: '^lightGallery',
        link: function (scope, element, attrs, ctrl) {

            if (scope.$last) {
                ctrl.initGallery();
            }

        }
    }
})

生成的标记(通过在初始化 Light Gallery 时指定 selector 选项,实际上可以是您想要的任何内容):

<ul light-gallery gallery-options="galleryOptions">
    <li ng-repeat="photo in album.photos" data-src="{{photo.fullres}}" light-gallery-item>
        <img ng-src="{{photo.thumbnail}}" />
    </li>
</ul>

而选项可以是任何有效的 Light Gallery 选项,例如:

$scope.galleryOptions = {
    selector: '.file-trigger',
    ...
};