我正在寻找一种观察窗口内部宽度大小变化的方法。我尝试了以下操作,但没有成功:
$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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句