在指令 $(window).load 中使用 jQuery 插件
Using jQuery plugin within directive $(window).load
目前我正在尝试在 AngularJS 指令中使用此插件 https://github.com/zurb/twentytwenty。
当我第一次加载我的应用程序时,一切正常,但由于插件在 $(window).load
之后运行并且我的应用程序是 SPA,它只执行一次。这意味着当我离开视图并稍后返回时,插件将停止工作。
我的指令是这样的:
.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();
});
}
}
})
我还在学习 AngularJS,这是我第一次在指令中使用 jQuery 插件,所以我完全不知道如何解决这个问题。 :(
您应该将它同时放在 element.load
和 $window.load
上,这样每次渲染元素和 window 加载时它都会触发。
您需要从 $window.load
事件中设置 element.on('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();
});
}
}
}])
目前我正在尝试在 AngularJS 指令中使用此插件 https://github.com/zurb/twentytwenty。
当我第一次加载我的应用程序时,一切正常,但由于插件在 $(window).load
之后运行并且我的应用程序是 SPA,它只执行一次。这意味着当我离开视图并稍后返回时,插件将停止工作。
我的指令是这样的:
.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();
});
}
}
})
我还在学习 AngularJS,这是我第一次在指令中使用 jQuery 插件,所以我完全不知道如何解决这个问题。 :(
您应该将它同时放在 element.load
和 $window.load
上,这样每次渲染元素和 window 加载时它都会触发。
您需要从 $window.load
事件中设置 element.on('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();
});
}
}
}])