bothib
bothib

Reputation: 13

Set scope variable inside $window function

I want to set $scope.columns depends on windows size. If statement works well, but in $window function i don't have access to the scope variables. What should i try?

.controller("mainController", function($window, $scope) {

  $window.onresize = function() {
    var screenWidth = $window.innerWidth;
    if (screenWidth < 1285) {
      $scope.columns = 1;
    } else if (1767 > screenWidth && screenWidth >= 1285) {
      $scope.columns = 2;
    } else if (2249 > screenWidth && screenWidth >= 1767) {
      $scope.columns = 3;
    } else if (2731 > screenWidth && screenWidth >= 2249) {
      $scope.columns = 4;
    } else if (3213 > screenWidth && screenWidth >= 2249) {
      $scope.columns = 5;
    } else if (screenWidth >= 3213) {
      $scope.columns = 6;
    }
  }
})

Upvotes: 1

Views: 857

Answers (2)

Tamas Hegedus
Tamas Hegedus

Reputation: 29916

You definitely can access the $scope variables. The problem is that the $window.onresize event is not supervised by angular, so the changes are made, but are not reflected on the UI until the next digest. You will have to notify angular about a change being made by $scope.$apply(). Try this:

.controller("mainController", function($window, $scope) {
  $window.onresize = function() {
    $scope.$apply(function() {
      var screenWidth = $window.innerWidth;
      if (screenWidth < 1285) {
        $scope.columns = 1;
      } else if (1767 > screenWidth && screenWidth >= 1285) {
        $scope.columns = 2;
      } else if (2249 > screenWidth && screenWidth >= 1767) {
        $scope.columns = 3;
      } else if (2731 > screenWidth && screenWidth >= 2249) {
        $scope.columns = 4;
      } else if (3213 > screenWidth && screenWidth >= 2249) {
        $scope.columns = 5;
      } else if (screenWidth >= 3213) {
        $scope.columns = 6;
      }
    });
  }
})

Upvotes: 2

taxicala
taxicala

Reputation: 21759

I believe that the function will be executed in the window scope when the event fires, you can try to set the scope to a controller attribute, and bind the function to the controller:

.controller("mainController", function($window, $scope) {
  this.scope = $scope;
  $window.onresize = function() {
    var screenWidth = $window.innerWidth;
    if (screenWidth < 1285) {
      this.scope.columns = 1;
    } else if (1767 > screenWidth && screenWidth >= 1285) {
      this.scope.columns = 2;
    } else if (2249 > screenWidth && screenWidth >= 1767) {
      this.scope.columns = 3;
    } else if (2731 > screenWidth && screenWidth >= 2249) {
      this.scope.columns = 4;
    } else if (3213 > screenWidth && screenWidth >= 2249) {
      this.scope.columns = 5;
    } else if (screenWidth >= 3213) {
      this.scope.columns = 6;
    }
  }.bind(this);
})

Upvotes: 1

Related Questions