在ui中执行某些操作之前,AngularJS范围不会更新,例如单击具有函数的对象

Joe*_*ito 6 javascript digest angularjs angularjs-scope

当视口小于或等于641px时,我试图将类添加到我的侧边栏,我必须观察该窗口的宽度

    $scope.$watch(function(){
       return $window.innerWidth;
    }, function(value) {
        if (value <= 641) {
            logger.info('!!!less than 641');
            vm.singleColumn = true;
        };
    });
Run Code Online (Sandbox Code Playgroud)

它会在第一次加载时登录,但是当我调整大小时,我必须在它再次触发之前进行一些点击.例如,我调整了大小,然后点击了具有ng-click行为的项目,那是唯一一次,它再次记录.

我已经阅读了一些问题,这可能是由于$ digest和$ apply?

有人可以解释我的困惑.

dz2*_*210 6

您需要触发摘要循环,否则视图不会意识到值已更新。

$scope.$watch(function(){
   return $window.innerWidth;
}, function(value) {
    if (value <= 641) {
        logger.info('!!!less than 641');
        vm.singleColumn = true;
        $scope.$apply();
    };
});
Run Code Online (Sandbox Code Playgroud)


use*_*084 1

根据我的说法,您可以尝试指令并使用 jquery 检查窗口大小调整并相应地更新您的变量。我在这里有一个例子请检查

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();
        });
    }
})
Run Code Online (Sandbox Code Playgroud)
div {
    border:1px solid red;
}
Run Code Online (Sandbox Code Playgroud)
<div ng-app="miniapp" ng-controller="AppController" ng-style="style()" resize>window.height: {{windowHeight}}
    <br />window.width: {{windowWidth}}
    <br />
</div>
Run Code Online (Sandbox Code Playgroud)

小提琴

请告诉我这是否有效