在指令$(window.load)中使用jQuery插件
目前,我正在尝试在AngularJS指令中使用这个插件 当我第一次加载我的应用程序时,一切正常,但是由于插件在在指令$(window.load)中使用jQuery插件,jquery,angularjs,angularjs-directive,twentytwenty,Jquery,Angularjs,Angularjs Directive,Twentytwenty,目前,我正在尝试在AngularJS指令中使用这个插件 当我第一次加载我的应用程序时,一切正常,但是由于插件在$(window.load)之后运行,所以我的应用程序是SPA,它只执行一次。这意味着当我离开视图,稍后再回来时,插件停止工作 我的指令如下所示: .directive('ngCompare', function() { return { cache: false, restrict: 'A', replace: true, scope: { img1: '=',
$(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();
});
}
}
})
指令('ngCompare',函数(){
返回{
cache:false,
限制:“A”,
替换:正确,
范围:{
img1:“=”,
img2:“=”
},
模板:“”+
"" +
"" +
"",
链接:函数(范围、元素、属性){
$(窗口)。加载(函数(){
$(元素).twentytwenty();
});
}
}
})
我还在学习AngularJS,这是我第一次在指令中使用jQuery插件,所以我完全不知道如何解决这个问题(您应该将它放在
元素.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();
});
}
}
}])
.directive('ngCompare',['$window',function($window){
返回{
cache:false,
限制:“A”,
替换:正确,
范围:{
img1:“=”,
img2:“=”
},
模板:“”+
"" +
"" +
"",
链接:函数(范围、元素、属性){
var setElementLoadEvent=function(){
on('load',function(){
元素。twentytwenty();
});
};
$window.load(函数(){
元素。twentytwenty();
setElementLoadEvent();
});
}
}
}])
您好,谢谢您的回答。我尝试了您的代码,但仍然无法使用,因为$(窗口)。load
仅在应用程序开始时调用,而不是在您返回到已打开的视图时调用。@KevinSleegers元素。on('load')
是否被调用?不,它没有。我添加了控制台.log('test')
在元素中。在('load')
上,但这不会出现在控制台中。您是否只加载ngCompare
一次或多次?太棒了!我添加了一个范围。$watchGroup
用于观看img1
和img2
,现在工作正常了!非常感谢您的帮助:)