Matthew Daly
Matthew Daly

Reputation: 9476

Event to use for binding Angular directive on image load

I'm trying to integrate this jQuery plugin into an Ionic app. I'm comfortable with the idea of creating an Angular directive to wrap the plugin, but I'm struggling to get it working.

Here's the directive:

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'
            });
          });
        } 
    };
}]);

And here's the relevant template:

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

The photos are fetched using an AJAX request, and then pulled in using ng-repeat.

Using the Chrome debugger I've been able to establish that the link function gets called, but the function that binds to the load event never gets called. So presumably I'm not binding to the correct event.

Given that I want the images to finish loading before I initialise the jQuery plugin, what event should I be binding to?

Upvotes: 0

Views: 140

Answers (2)

null
null

Reputation: 7926

Sadly there's no builtin event that fires when a ng-repeat has completed. You can however create a simple directive that does this trick:

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

Apply it on the img elements inside the ng-repeat and you're good to go.

See this plunker as proof.

Upvotes: 1

MrNobody007
MrNobody007

Reputation: 1837

You need to bind load event to IMG tag instead of the DIV. Replace elem with 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'
                });
              });
            } 
        };
    }]);

Upvotes: 1

Related Questions