如何使AngularJS指令操纵与之关联的所有元素?

时间:2014-06-14 04:37:26

标签: javascript angularjs angularjs-directive dom-manipulation window-resize

我有一个指令可以修改它关联的'element'的宽度。它在第一页加载时效果很好,但是我希望它根据窗口的大小来改变宽度。我添加了一个'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
  };
});

2 个答案:

答案 0 :(得分:2)

@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

答案 1 :(得分:1)

这是因为每次指令运行其链接函数时,您都会重新分配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) - 不要记得这样的事情是否有效。