我如何使用 AngularJS 对窗口大小的变化做出反应



我以此作为监视窗口大小调整事件的一种方式。 但是它的工作非常缓慢。有人可以建议他们是否知道其他一些简单且不涉及复杂指令的方法。也非常感谢任何关于我这样做的方式是否是一种好方法的建议。

 $scope.$watch(($scope) => {
    $scope.isLarge = $window.innerWidth > 650 ? true : false;
    angular.element($window).on('resize', () => {
       $scope.$digest();
    });
    console.log($scope.isLarge);
 });

工作小提琴:https://jsfiddle.net/jaredwilli/SfJ8c/

.HTML

<div ng-app="miniapp" ng-controller="AppController" ng-style="style()" resize>window.height: {{windowHeight}}
    <br />window.width: {{windowWidth}}
    <br />
</div>

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();
        });
    }
})

最新更新