Karly
Karly

Reputation: 389

Window innerWidth size change

I'm using the $watch listener function to check changes on the window inner width with the following code:

$scope.$watch(function(){
   return $window.innerWidth;
}, function(value) {
   if(value <= 768){
        $scope.mobileSize = "mobile";      
   }else{
        $scope.mobileSize = "screen";
   }
   console.log(value);
});

it should then act on the DOM with some ng-show conditions like this one for example :

                <div ng-show="mobileSize == 'screen'">
                    ...
                </div>  

But it only seems to affect the page when I reload it after resizing it. The console.log(value) also only changes when I refresh the page.

Is there any way to make this code work while the window is being resized ?

Upvotes: 1

Views: 2675

Answers (1)

JME
JME

Reputation: 3642

Personally, I'm not a fan of using $watch because of its inefficiency. That said, if you're already using jQuery (or you're willing to use it) together with Angular, you can try this in your controller:

function setMobileSize(value) {
   console.log(value);
   if(value <= 350){
        $scope.mobileSize = "mobile";      
   }else{
        $scope.mobileSize = "screen";
   }
};

setMobileSize($window.innerWidth);

$(window).resize(function(){
    $scope.$apply(function(){
        setMobileSize($window.innerWidth);    
    });
});

EDIT:

If you do not wish to use jQuery, you may bind to the resize event directly.

angular.element($window).bind('resize',function(){
    $scope.$apply(function(){
        setMobileSize($window.innerWidth);    
    });
});

Upvotes: 1

Related Questions