Skip to content

Instantly share code, notes, and snippets.

@13protons
Last active August 29, 2015 14:27
Show Gist options
  • Save 13protons/609aec08388c110f432f to your computer and use it in GitHub Desktop.
Save 13protons/609aec08388c110f432f to your computer and use it in GitHub Desktop.
Angular module that allows controllers to inspect screensize by bootstrap breakpoint names.

Angular Bootstrap Screen Size

An angular module to report on bootstrap's reponsive grid breakpoints. The injected html snipped uses bootstrap's named breakpoints so your script doesn't need to know anything about the actual css dimensions.

Install

  1. Include ScreenSize as a dependency of your app
  2. Reference ScreenSizeFactory in your controler's DI list
  angular
    .module('yourMod', ['ScreenSize'])
    .controller('yourModCtrl, function(ScreenSizeFactory){
      ...
    }

Usage

var screenSize = ScreenSizeFactory.name(); // returns 'xs', 'sm', 'md', or 'lg'
if( ScreenSizeFactory.if('md') ){
  //do something only at the 'md' screen size
}

## Gotchya

This may cause tests to fail for controllers that depend on `ScreenSizeFactory` when use a headless environment like PhantomJS. 

> 2015 @alanguir
/************
Angular Bootstrap Screen Size
=============================
An angular module to report on bootstrap's reponsive grid breakpoints. The injected html snipped uses bootstrap's named breakpoints so your script doesn't need to know anything about the actual css dimensions.
2015 @alanguir
************/
angular.module('ScreenSize', [])
.run(function (){
angular.element(document).find('body').append('<div id="_breakpoints"><span class="visible-xs-block" data-name="xs"></span><span class="visible-sm-block" data-name="sm"></span><span class="visible-md-block" data-name="md"></span><span class="visible-lg-block" data-name="lg"></span></div>')
})
.factory('ScreenSizeFactory', function(){
var canary = angular.element(document).find('#_breakpoints span');
var factory = {};
if(false && typeof($.filter) == 'function'){
//things are a bit simpler with jQuery
factory.name = function(){
return $('#_breakpoints span').filter(":visible").data('name');
}
} else {
// no jquery? that's ok, we can still figure it out
factory.name = function(){
var name = '';
angular.forEach(canary, function(val, i){
if(val.offsetParent) {
name = angular.element(val).data('name');
}
});
return name;
}
}
factory.if = function(name){
return factory.name() == name
}
return factory;
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment