简体   繁体   English

在指令$(window).load中使用jQuery插件

[英]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. 目前,我正在尝试在AngularJS指令中使用此插件https://github.com/zurb/twentytwenty

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. 当我第一次加载我的应用程序时,一切正常,但是由于该插件在$(window).load之后运行,并且我的应用程序是SPA,因此它只执行一次。 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. 我仍在学习AngularJS,这是我第一次在Directive中使用jQuery插件,因此我完全不知道如何解决此问题。 :( :(

You should place it on element.load & $window.load both, so it will fire every time when element gets rendered & window gets loaded. 您应该将其同时放置在element.load$window.load ,因此每次渲染元素和加载窗口时都会触发它。

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 您需要从$window.load事件中设置element.on('load')事件,以确保该事件仅在指令的启动时触发一次

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM