Kevin
Kevin

Reputation: 495

Using jQuery plugin within directive $(window).load

At the moment I'm trying to use this plugin https://github.com/zurb/twentytwenty within a AngularJS Directive.

When I load my application for the first time everything works fine, but since the plugin runs after $(window).load and my app is a SPA it executes only once. That means when I leave the view and come back at a later point, the plugin stops working.

My Directive looks like this:

.directive('ngCompare', function() {
return {
  cache: false,
  restrict: 'A',
  replace: true,
  scope: {
    img1: '=',
    img2: '='
  },
  template: "<div id='container1'>" +
  "<img ng-src='{{img1}}'>" +
  "<img ng-src='{{img2}}'>" +
  "</div>",
  link: function(scope, element, attrs) {
    $(window).load(function(){
      $(element).twentytwenty();
    });
  }
}
})

I'm still learning AngularJS and this is my first time using a jQuery plugin within a Directive, so I have absolutely no idea how to solve this. :(

Upvotes: 1

Views: 1062

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

You should place it on element.load & $window.load both, so it will fire every time when element gets rendered & window gets loaded.

You need to set element.on('load') event from the $window.load event, so it will ensure the event will fire once only at starting kick of directive

Directive

.directive('ngCompare',['$window', function($window) {
    return {
        cache: false,
        restrict: 'A',
        replace: true,
        scope: {
            img1: '=',
            img2: '='
        },
        template: "<div id='container1'>" +
            "<img ng-src='{{img1}}'>" +
            "<img ng-src='{{img2}}'>" +
            "</div>",
        link: function(scope, element, attrs) {
            var setElementLoadEvent = funcion() {
                element.on('load', function() {
                    element.twentytwenty();
                });
            };
            $window.load(function() {
                element.twentytwenty();
                setElementLoadEvent();
            });
        }
    }
}])

Upvotes: 1

Related Questions