codephobia
codephobia

Reputation: 1590

ng-class $window.innerWidth

I am trying to find a solution to add a class to an item if the screen width is greater than x (ie. 1200).

ng-class="{ large: isLarge() }"

$scope.isLarge = function () {
  return ($window.innerWidth >= 1200);
}

This doesn't work, and wont even add the class. It also needs to update on browser resize. Thinking a directive might be a better option.

EDIT: I don't want to hear if this should be done, just if it can be done.

Upvotes: 3

Views: 5240

Answers (1)

scniro
scniro

Reputation: 16979

You could do this. I have crafted a directive example which accomplishes this. I chose a width of 500 in this example for an easier JSFiddle demo. Check out the following...

<div class="item" resizer></div>

.item {
    background-color: tomato;
    height: 100px;
    width: 100px;
}

.large {
    background-color: dodgerblue;
}

app.directive('resizer', ['$window', function ($window) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {            
            angular.element($window).on('resize', function () {
                $window.innerWidth > 500 ? 
                    elem.addClass('large') : elem.removeClass('large')
            });
        }
    }
}]);

JSFiddle Example

Furthermore, if you wish to leverage a ng-class solution, give the following a shot...

<div class="item" resizer ng-class="{ 'large': isLarge }"></div>

app.directive('resizer', ['$window', function ($window) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {      
            angular.element($window).on('resize', function () {
                scope.$apply(function(){
                    scope.isLarge = $window.innerWidth > 500 ? true : false;
                })
            });
        }
    }
}]);

JSFiddle Example - with ng-class

Upvotes: 6

Related Questions