gpt4 book ai didi

javascript - 我如何使 AngularJS 指令操纵与其关联的所有元素?

转载 作者:行者123 更新时间:2023-11-30 12:41:41 24 4
gpt4 key购买 nike

我有一个指令可以修改其关联“元素”的宽度。它在第一页加载时效果很好,但我希望它根据窗口的大小更改宽度。我添加了一个“window.onresize”函数,但它只会影响与该指令关联的最后一个元素。为什么它没有影响到所有人?

这是我的指令代码,这是一个 plunker:

http://plnkr.co/edit/ytXSY1gtxQRAVLEHxRMY?p=preview

angular.module('app', ['components'])
angular.module('components', [])

.directive('gallerySlide', function() {
function link(scope, element, attrs) {
function resize() {
element[0].style.width = window.innerWidth - 300 + 'px';
}
resize();
window.onresize = resize;
}
return {
link: link
};
});

最佳答案

@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);
});
}
};
});

DEMO

关于javascript - 我如何使 AngularJS 指令操纵与其关联的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24216615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com