[英]How can I react to changes in window size with AngularJS?
I have this as a way to watch for a window resize event. 我用这种方法来监视窗口调整大小事件。 However it works very slowly. 但是,它的工作非常缓慢。 Can someone advise if they know of some other way that is simple and does not involve a complicated directive. 有人可以建议他们是否知道其他简单且不涉及复杂指令的方式。 Also would appreciate any suggestions on if the way I am doing it is a good way. 如果我正在做的这是一个好方法,也将不胜感激。
$scope.$watch(($scope) => {
$scope.isLarge = $window.innerWidth > 650 ? true : false;
angular.element($window).on('resize', () => {
$scope.$digest();
});
console.log($scope.isLarge);
});
Working Fiddle: https://jsfiddle.net/jaredwilli/SfJ8c/ 工作小提琴: https : //jsfiddle.net/jaredwilli/SfJ8c/
HTML 的HTML
<div ng-app="miniapp" ng-controller="AppController" ng-style="style()" resize>window.height: {{windowHeight}}
<br />window.width: {{windowWidth}}
<br />
</div>
JavaScript 的JavaScript
var app = angular.module('miniapp', []);
function AppController($scope) {
/* Logic goes here */
}
app.directive('resize', function ($window) {
return function (scope, element) {
var w = angular.element($window);
scope.getWindowDimensions = function () {
return {
'h': w.height(),
'w': w.width()
};
};
scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
scope.windowHeight = newValue.h;
scope.windowWidth = newValue.w;
scope.style = function () {
return {
'height': (newValue.h - 100) + 'px',
'width': (newValue.w - 100) + 'px'
};
};
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.