AngularJS - ng-show with scope variable changed

I try to hide / show certain things when the orientation of the phone changes.

Here is my view:

<div ng-controller="ModelCtrl">
    <p ng-show="isLandscape">Landscape - {{ isLandscape }}</p>
    <p ng-show="!isLandscape">Portrait - {{ !isLandscape }}</p>
</div>

And here is the controller fragment:

    $scope.isLandscape = false;

    // Listen for orientation changes
    window.addEventListener("orientationchange", function() {
        // Announce the new orientation number
        switch(window.orientation) 
        {  
          case -90:
          case 90:
            $scope.isLandscape = true;
            alert($scope.isLandscape);
            break; 
          default:
            $scope.isLandscape = false;
            alert($scope.isLandscape);
            break; 
        }
    }, false);

I can warn the correct value of isLandscape when the orientation changes, but it seems that it does not update the view, so it always says this in "portrait mode - true".

+4
source share
1 answer

You are absent$scope.$apply() :

$scope.isLandscape = false;

// Listen for orientation changes
window.addEventListener("orientationchange", function() {
    // Announce the new orientation number
    switch(window.orientation) 
    {  
      case -90:
      case 90:
        $scope.isLandscape = true;
        $scope.$apply(); // <--
        break; 
      default:
        $scope.isLandscape = false;
        $scope.$apply(); // <--
        break; 
    }
}, false);

Once you change the value, Angular does not know that it should check if the value has changed or not. $scope.$applywill trigger a digest loop that will give Angular a notice of what $scope.isLandscapehas changed.


$window orientationchange. $scope.$apply.

+7

All Articles