Javascript 如何使AngularJS指令操作与其关联的所有元素?
我有一个指令修改它的相关“元素”的宽度。它在第一页加载时非常有效,但我希望它根据窗口的大小来改变宽度。我添加了一个“window.onresize”函数,但它只会影响与该指令关联的最后一个元素。为什么它没有影响到他们所有人 这是我的指令代码,这是一个plunker:Javascript 如何使AngularJS指令操作与其关联的所有元素?,javascript,angularjs,angularjs-directive,dom-manipulation,window-resize,Javascript,Angularjs,Angularjs Directive,Dom Manipulation,Window Resize,我有一个指令修改它的相关“元素”的宽度。它在第一页加载时非常有效,但我希望它根据窗口的大小来改变宽度。我添加了一个“window.onresize”函数,但它只会影响与该指令关联的最后一个元素。为什么它没有影响到他们所有人 这是我的指令代码,这是一个plunker: 这是因为每次指令运行其链接函数时,您都在分配onresize侦听器 在这里: 编辑: .directive('gallerySlide', function() { var elements = []; functio
这是因为每次指令运行其链接函数时,您都在分配
onresize
侦听器
在这里:
编辑:
.directive('gallerySlide', function() {
var elements = [];
function resize () {
elements.forEach(function (element) {
element.style.width = window.innerWidth - 300 + 'px';
});
};
window.onresize = resize;
function link(scope, element, attrs) {
elements.push(element[0]);
resize();
}
return {
link: link
};
});
顺便说一下,尝试其他绑定到
window.onresize
的方法。也许注入$window
而不是做一些$window.on('resize',resize)
–但是,不要回忆起这样的事情是否有效/存在。@gtramontina关于每次运行链接函数时重新分配onresize
是正确的。在这里,我建议使用jQuery管理事件队列的另一种解决方案,记住通过处理作用域的$destroy
事件来避免内存泄漏:
.directive('gallerySlide', function() {
return {
link: function link(scope, element, attrs) {
var id = Math.random(); //generate random id so that we can un-register event handler to avoid memory leaks.
function resize()
{
element[0].style.width = window.innerWidth - 300 + 'px';
}
resize();
$(window).on("resize",id,resize);
scope.$on("$destroy",function(){ //this is important to avoid memory leaks.
$(window).off("resize",id);
});
}
};
});
.directive('gallerySlide', function() {
return {
link: function link(scope, element, attrs) {
var id = Math.random(); //generate random id so that we can un-register event handler to avoid memory leaks.
function resize()
{
element[0].style.width = window.innerWidth - 300 + 'px';
}
resize();
$(window).on("resize",id,resize);
scope.$on("$destroy",function(){ //this is important to avoid memory leaks.
$(window).off("resize",id);
});
}
};
});