Ng-class $ window.innerWidth
I am trying to find a solution to add a class to an element if the screen width is greater than x (i.e. 1200).
ng-class="{ large: isLarge() }"
$scope.isLarge = function () {
return ($window.innerWidth >= 1200);
}
It doesn't work and doesn't even add a class. You also need to update the browser size. Thinking about a directive might be the best option.
EDIT: I don't want to hear if it should be done, only if it can be done.
+3
source to share
1 answer
Can you do it. I have developed an example directive that accomplishes this. In this example, I chose a width of 500 for an easier JSFiddle demo. Check 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')
});
}
}
}]);
Also, if you want to use the solution ng-class
, give the following 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 - usingng-class
+5
source to share