[英]How do I make an AngularJS directive manipulate all elements associated with it?
我有一個指令,修改它的相關'元素'的寬度。 它在第一頁加載時效果很好,但是我希望它根據窗口的大小來改變寬度。 我添加了一個'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);
});
}
};
});
那是因為每次指令運行其鏈接函數時,您都會重新分配onresize
偵聽器。
這里: http : //plnkr.co/edit/CCHgndK4cxCBMUfzTeil?p =preview
編輯:
.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)
- 不要記得這樣的事情是否有效/存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.