2

我有一个必须以横向查看的网络应用程序。

为此,我创建了一个检查innerWidthand的函数,innderHeight如果宽度大于高度,那么快乐的日子。这在我加载页面时非常有效,但我也可以在resize事件触发时检查方向。

所以我的代码流程是 -

  1. 在触发resize事件调用时$scope.getOrienttion()
  2. 计算当前方向并返回结果
  3. 监视$scope.getOrienttion()使用 a的值的变化watch并更新 的值$scope.orientation

上面的第 1 步和第 2 步似乎工作正常,但我watch从未检测到更改,$scope.getOrienttion()并且仅在页面加载时触发。我一定是做错了什么,谁能帮我找出问题所在。

这是相关的AngularJS -

christmasApp.controller('bodyCtrl', function($scope, $window){

    angular.element($window).bind('resize', function(){
        console.log('Event triggered');
        $scope.getOrientation();
    });

    $scope.getOrientation = function(){

        var w = $window.innerWidth,
            h = $window.innerHeight;
        var orientation = (w > h) ? 'landscape' : 'portrait'
        console.log('Function triggered - ' + orientation)
        return (w > h) ? 'landscape' : 'portrait';

    };

    $scope.$watch($scope.getOrientation, function(newValue, oldValue){
        $scope.orientation = newValue;
        console.log('Watch triggered - ' + newValue);
    }, true);

});

这是具有条件类集的 HTML,具体取决于$scope.orientation(可能不相关,但以防万一)的值 -

<body <?php body_class(); ?> data-ng-controller="bodyCtrl">

    <div id="orientationMask" data-ng-class="{visible: orientation != 'landscape'}">
        <p>Please turn your device to the <b>landscape</b> orientation.</p>
    </div>

    { Additional code, obscured by the mask if it is show... }

</body>
4

2 回答 2

2

getOrientation虽然从事件调用resize只是执行getOrientation代码,但它并不暗示某些事情发生了变化。所以你需要打电话告诉 Angular 来运行摘要循环$apply()$scope调用摘要循环后,角度将评估所有$watchers 并且您的观察者函数将被评估。

getOrientation实际上,来自事件的方法调用似乎resize没有做任何与范围级别绑定相关的事情。因此,您可以从那里删除该getOrientation方法,因为它似乎调用了一个在那里什么都不做的代码。

代码

angular.element($window).bind('resize', function(){
    console.log('Event triggered');
    $scope.getOrientation(); //you could remove this method, as its not modifying any scope
    //will run digest cycle, and the watcher expression will get evaluated
    $scope.$apply(); //you could also use $timeout(function(){}) here run safe digest cycle.
});
于 2015-12-05T16:18:15.617 回答
1

你为什么不听这样的orientationchange事件呢?

    window.addEventListener("orientationchange", function() {
            switch(window.orientation){  
            case -90:
            case 90:
                $rootScope.orientation = "landscape";
                break; 
            default:
                $rootScope.orientation = "portrait";
            break; 
            };

    }, false);
于 2015-12-05T16:34:09.067 回答