14

Is it possible to use ng-if to very simply not load an element for smaller screen sizes?

4
  • 1
    Seems like a CSS media query would be simpler. Commented Mar 19, 2015 at 21:39
  • 1
    If you really need to, you can you the $window service to get the actual window and ng-if from there. Commented Mar 19, 2015 at 21:41
  • 6
    I'm also using bootstrap, so hiding things is easy. I was just thinking since ng-if doesn't just hide items but excludes them from the DOM it would save on mobile load times. Commented Mar 20, 2015 at 0:25
  • How do you use the $window service? Commented Mar 20, 2015 at 0:25

2 Answers 2

11

You can use angular-match-media for that.

In your controller you can create variables that correspond to screen sizes. For example add the following to your controller:

// Using static method `is`
angular.module('myApp', ['matchMedia'])
.controller('mainController', ['screenSize', function(screenSize) {
  $scope.isScreenSize = screenSize.is;
}]);

Then in your HTML you can show or hide content using ngIf or similar directives that take an Angular expression:

<img ng-if="isScreenSize('md, lg')" ng-src='http://example.com/path/to/giant/image.jpg'>

This particular example is great for only loading large, unnecessary images on desktop computers.

Note: It's important if you plan on using screensize.is() in directives to assign its return value to a scoped variable. If you don't, it will only be evaluated once and will not update if the window is resized or if a mobile device is turned sideways.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice! I'd even go one step further and making your own version of this plugin for maximum control. Could even be a directive usable in a similar way that bootstrap adds hidden-sm classes. i.e hide-if-mobile, show-if-iphone hide-if-desktop etc etc
6

An alternative to ng-if, is if you are using Angular Material for your layout they provide directives hide and show to control visibility of elements based on screen size.

For example:

<div hide-gt-sm>You'll only see me on small screens</div>
<div show-gt-lg>You'll only see me on big screens</div>

Docs:

https://material.angularjs.org/latest/layout/options

1 Comment

That solution only hide the element (display:none). He want to remove from the DOM, the best solution for me was using angular-match-media.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.