窗口innerWidth大小更改时的AngularJS事件

窗口innerWidth大小更改时的AngularJS事件,第1张

窗口innerWidth大小更改时的AngularJS事件

我们可以使用jQuery来做到这一点:

$(window).resize(function(){    alert(window.innerWidth);    $scope.$apply(function(){       //do something to update current scope based on the new innerWidth and let angular update the view.    });});

请注意,将事件处理程序绑定在可以 重新创建的 范围内(例如ng-
repeat范围,指令范围等)时,在销毁该范围时应取消绑定事件处理程序。如果不执行此 *** 作,则每次重新创建作用域(重新运行控制器)时,都会再添加1个处理程序,从而导致意外行为和泄漏。

在这种情况下,您可能需要标识附加的处理程序:

  $(window).on("resize.doResize", function (){      alert(window.innerWidth);      $scope.$apply(function(){          //do something to update current scope based on the new innerWidth and let angular update the view.      });  });  $scope.$on("$destroy",function (){      $(window).off("resize.doResize"); //remove the handler added earlier  });

在此示例中,我使用的是jQuery中的事件名称空间。您可以根据自己的要求进行不同的处理。

改进 :如果您的事件处理程序需要花费很长的时间来处理,为避免用户可能会不断调整窗口大小,导致事件处理程序多次运行,我们可以考虑对函数进行
节流 。如果使用下划线,则可以尝试:

$(window).on("resize.doResize", _.throttle(function (){    alert(window.innerWidth);    $scope.$apply(function(){        //do something to update current scope based on the new innerWidth and let angular update the view.    });},100));

取消 功能:

$(window).on("resize.doResize", _.debounce(function (){     alert(window.innerWidth);     $scope.$apply(function(){         //do something to update current scope based on the new innerWidth and let angular update the view.     });},100));


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5642009.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存