Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use ng-if for display size

Tags:

angularjs

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

like image 990
Jared Whipple Avatar asked Mar 19 '15 21:03

Jared Whipple


People also ask

What is the use of NG-if?

The ng-if Directive in AngularJS is used to remove or recreate a portion of the HTML element based on an expression. The ng-if is different from the ng-hide directive because it completely removes the element in the DOM rather than just hiding the display of the element.

Can we use data Ng instead of Ng-If we want to make your page HTML valid?

You can use data-ng-, instead of ng-, if you want to make your page HTML valid. You will learn a lot more about directives later in this tutorial.

What is Div ng-if?

Definition and Usage. The ng-if directive removes the HTML element if the expression evaluates to false. If the if statement evaluates to true, a copy of the Element is added in the DOM.


2 Answers

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.

like image 59
mrded Avatar answered Sep 18 '22 12:09

mrded


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

like image 21
codemonkey Avatar answered Sep 17 '22 12:09

codemonkey