Last active
August 29, 2015 14:21
-
-
Save schuyberg/034a9982bf8326c19fc9 to your computer and use it in GitHub Desktop.
AngularJS & EnquireJS Media Query Service
This file contains hidden or 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
// Example Service detects a max width of 400px | |
// use watch & unwatch functions to set or remove breakpoint listeners | |
// use ismatch & notmatch functions (callbacks) to act on breakpoint changes | |
services.factory('max400', ['$rootScope', '$timeout', function ($rootScope, $timeout) { | |
var max400 = { | |
watch: function() { enquire.register('screen and (max-width: 400px)', max400handler); }, | |
unwatch: function() { enquire.unregister('screen and (max-width: 400px)'); }, | |
ismatch: function(callback) { $rootScope.$on('match400', callback); }, | |
notmatch: function(callback) { $rootScope.$on('unmatch400', callback); }, | |
}; | |
var max400handler = { | |
match: function() { | |
$timeout(function(){ // timeout ensures that this fires after your controller has loaded | |
$rootScope.$emit('match400'); | |
}); | |
}, | |
unmatch: function(){ | |
$rootScope.$emit('unmatch400'); | |
} | |
}; | |
return max400; | |
}]); |
This file contains hidden or 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
// In your controller use: | |
max400.watch(); // register enquire breakpoint | |
max400.ismatch(function(){ | |
$scope.max400 = true; | |
console.log('MAX 400 TRUE'); | |
}); | |
max400.notmatch(function(){ | |
$scope.max400 = false; | |
console.log('MAX 400 FALSE'); | |
}); | |
// to disable (if you switch to a page where it is uncessary, for instance): | |
max400.unwatch(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment