1

'요소'와 연결된 너비를 수정하는 지시문이 있습니다. 첫 페이지로드시 잘 작동하지만 창 크기에 따라 너비를 변경하고 싶습니다. 'window.onresize'함수를 추가했지만 지시문과 관련된 마지막 요소에만 영향을 미칩니다. 왜 그것들 모두에 영향을 미치지 않는가?AngularJS 지시문을 사용하여 관련된 모든 요소를 ​​조작하는 방법은 무엇입니까?

여기 내 지시 코드이며, 여기에 plunker입니다 : 당신은 때문에 onresize 청취자에게 지침이 링크 기능을 실행할 때마다 재 할당의

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

답변

2

@gtramontina는 링크 기능이 실행될 때마다 onresize이 다시 할당되는 것이 정확합니다.

.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

: 여기 이벤트 큐를 관리하고 범위의 $destroy 이벤트를 처리하여 메모리 누수을 방지하기 위해 기억 jQuery를 사용하여 다른 솔루션을 제안
1

. 여기

: 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.on('resize', resize)하는 것보다 - 그러한 것이 작동하는지/존재 하는지를 기억하지 마십시오.

관련 문제