窗口innerWidth大小更改上的AngularJS事件 [英] AngularJS event on window innerWidth size change

查看:24
本文介绍了窗口innerWidth大小更改上的AngularJS事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来观察窗口内部宽度大小的变化.我尝试了以下方法,但没有奏效:

I'm looking for a way to watch changes on window inner width size change. I tried the following and it didn't work:

$scope.$watch('window.innerWidth', function() {
     console.log(window.innerWidth);
});

有什么建议吗?

推荐答案

我们可以用 jQuery 做到:

We could do it with 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 个处理程序,导致意外行为和泄漏.

Be aware that when you bind an event handler inside scopes that could be recreated (like ng-repeat scopes, directive scopes,..), you should unbind your event handler when the scope is destroyed. If you don't do this, everytime when the scope is recreated (the controller is rerun), there will be 1 more handler added causing unexpected behavior and leaking.

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

In this case, you may need to identify your attached handler:

  $(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 的 事件命名空间.您可以根据自己的要求进行不同的操作.

In this example, I'm using event namespace from jQuery. You could do it differently according to your requirements.

改进:如果你的事件处理程序需要很长时间来处理,为了避免用户可能不断调整窗口大小,导致事件处理程序运行多次的问题,我们可以考虑限制功能.如果你使用下划线,你可以试试:

Improvement: If your event handler takes a bit long time to process, to avoid the problem that the user may keep resizing the window, causing the event handlers to be run many times, we could consider throttling the function. If you use underscore, you can try:

$(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));

限制和去抖动函数的区别

这篇关于窗口innerWidth大小更改上的AngularJS事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆