【问题标题】:How do I make an AngularJS directive manipulate all elements associated with it?如何让 AngularJS 指令操纵与其关联的所有元素?
【发布时间】:2014-08-04 16:19:04
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    @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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-02
        • 1970-01-01
        • 1970-01-01
        • 2019-03-25
        • 2014-09-02
        • 2015-01-26
        相关资源
        最近更新 更多