Created
March 26, 2014 19:57
-
-
Save seglo/9791838 to your computer and use it in GitHub Desktop.
DisplayModeService is a service that will notify consumers when the bootstrap display mode changes. Example Usage: DisplayModeService.on('visible-md', function() { $log.info('visible-md callback'); });
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
/* | |
* DisplayModeService is a service that will notify consumers when the bootstrap display mode changes. | |
* - heavily inspired by the following post: http://www.dnasir.com/2013/10/09/display-mode-detection-for-responsive-websites-using-angularjs/ | |
*/ | |
angular.module('myApp') | |
.service('DisplayModeService', function($window, $log) { | |
var markers = angular.element('<div class="visible-xs"></div><div class="visible-sm"></div><div class="visible-md"></div><div class="visible-lg"></div>'); | |
angular.element($window.document.body).append(markers); | |
var currentDisplayMode = 'visible-lg'; | |
var t; | |
angular.element($window).bind('resize', function() { | |
clearTimeout(t); | |
t = setTimeout(function() { | |
update(true); | |
}, 10); | |
}); | |
function update(notifyCallbacks) { | |
angular.forEach(markers, function(element) { | |
if (angular.element(element).is(":visible") && currentDisplayMode !== element.className) { | |
currentDisplayMode = element.className; | |
if (notifyCallbacks) { | |
notify(element.className); | |
} | |
return false; | |
} | |
}); | |
} | |
// set display mode once on instiantiation | |
update(false); | |
function notify(displayMode) { | |
$log.info('Bootstrap display mode is: ' + displayMode); | |
callbacks.filter(function(elm) { return elm.displayMode === displayMode; }).forEach(function(elm) { elm.callback(); }); | |
} | |
var callbacks = []; | |
this.on = function(displayMode, callback) { | |
callbacks.push({'displayMode':displayMode, 'callback': callback}); | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment