我正在寻找一种方法来观察窗口内部宽度大小变化的变化。我尝试了以下方法,但没有奏效:
$scope.$watch('window.innerWidth', function() {
console.log(window.innerWidth);
});
有什么建议?
我正在寻找一种方法来观察窗口内部宽度大小变化的变化。我尝试了以下方法,但没有奏效:
$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 的事件命名空间。你可以根据你的要求做不同的事情。
改进:如果您的事件处理程序需要很长时间来处理,为了避免用户可能不断调整窗口大小,导致事件处理程序运行多次的问题,我们可以考虑对功能进行节流。如果您使用underscore,您可以尝试:
$(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));
不需要jQuery!这个简单的片段对我来说很好用。它使用angular.element()来绑定窗口调整大小事件。
/**
* Window resize event handling
*/
angular.element($window).on('resize', function () {
console.log($window.innerWidth);
});
/**
* Window resize unbind event
*/
angular.element($window).off('resize');
我找到了一个可能在这里有帮助的 jfiddle:http : //jsfiddle.net/jaredwilli/SfJ8c/
我重构了代码以使其更简单。
// In your controller
var w = angular.element($window);
$scope.$watch(
function () {
return $window.innerWidth;
},
function (value) {
$scope.windowWidth = value;
},
true
);
w.bind('resize', function(){
$scope.$apply();
});
然后您可以从 html 中引用 windowWidth
<span ng-bind="windowWidth"></span>
如果 Khanh TO 的解决方案给您带来了 UI 问题(就像对我所做的那样),请尝试使用$timeout
不更新属性,直到它在 500 毫秒内保持不变。
var oldWidth = window.innerWidth;
$(window).on('resize.doResize', function () {
var newWidth = window.innerWidth,
updateStuffTimer;
if (newWidth !== oldWidth) {
$timeout.cancel(updateStuffTimer);
}
updateStuffTimer = $timeout(function() {
updateStuff(newWidth); // Update the attribute based on window.innerWidth
}, 500);
});
$scope.$on('$destroy',function (){
$(window).off('resize.doResize'); // remove the handler added earlier
});