1

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

4

1 回答 1

1

你应该把它放在element.load&上$window.load,所以每次渲染元素和加载窗口时它都会触发。

您需要element.on('load')从事件中设置事件$window.load,因此它将确保事件仅在指令开始时触发一次

指示

.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();
            });
        }
    }
}])
于 2015-05-01T09:32:21.140 回答