我们可以用 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
});
在这个例子中,我使用事件命名空间 http://api.jquery.com/on/来自 jQuery。您可以根据您的要求采取不同的做法。
改进:如果您的事件处理程序需要较长的处理时间,为了避免用户不断调整窗口大小,导致事件处理程序运行多次的问题,我们可以考虑节流功能。如果你使用下划线 http://underscorejs.org/#throttle, 你可以试试:
$(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));
or 去抖功能:
$(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://stackoverflow.com/questions/25991367/difference-between-throttling-and-debouncing-a-function