我正在寻找一种观察窗口内部宽度大小变化的方法。我尝试了以下操作,但没有成功:
$scope.$watch('window.innerWidth', function() { console.log(window.innerWidth); });
有什么建议?
我们可以使用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));