用于在图像加载时绑定 Angular 指令的事件

Event to use for binding Angular directive on image load

我正在尝试将 this jQuery plugin 集成到 Ionic 应用程序中。我对创建 Angular 指令来包装插件的想法很满意,但我正在努力让它工作。

指令如下:

angular.module('myapp.directives', [])

.directive('flipbook', ['$rootScope', function ($rootScope) { 
    return { 
        restrict: 'A',
        link: function (scope, elem, attrs) { 
          elem.bind('load', function () { 
            $(elem).flipbook({
              speed: 125,
              autoplay: false,
              play: 'button#playbutton',
              stop: 'button#pausebutton',
              rewind: 'button#rewindbutton'
            });
          });
        } 
    };
}]);

这是相关模板:

<ion-view view-title="{{ album.title }}">
<ion-content>

<div flipbook>
    <div class="gallery-item" ng-repeat="photo in album.photos | orderBy: 'created_at'">
        <img ng-if="photo.thumbnail" ng-src="{{ photo.thumbnail }}"></img>
    </div>                     
    </div>                     
</div>

</ion-content>
</ion-view>

照片是使用 AJAX 请求获取的,然后使用 ng-repeat 拉入。

使用 Chrome 调试器我已经能够确定 link 函数被调用,但是绑定到 load 事件的函数从未被调用。所以大概我没有绑定到正确的事件。

鉴于我希望在初始化 jQuery 插件之前完成图像加载,我应该绑定到什么事件?

您需要将 load 事件绑定到 IMG 标签而不是 DIV.将 elem 替换为 elem.find("img"):

angular.module('myapp.directives', []).directive('flipbook', ['$rootScope', function ($rootScope) { 
        return { 
            restrict: 'A',
            link: function (scope, elem, attrs) { 
              elem.find("img").bind('load', function () { 
                $(elem).flipbook({
                  speed: 125,
                  autoplay: false,
                  play: 'button#playbutton',
                  stop: 'button#pausebutton',
                  rewind: 'button#rewindbutton'
                });
              });
            } 
        };
    }]);

遗憾的是,在 ng-repeat 完成时没有触发内置事件。但是,您可以创建一个简单的指令来执行此操作:

app.directive('postRepeat', function() {
  return function(scope, element, attrs) {
    if (scope.$last){
      $('#book').flipbook();
    }
  };
});

将它应用到 ng-repeat 内的 img 元素上,就可以了。

请参阅此 plunker 作为证明。