Last active
August 29, 2015 14:16
-
-
Save mciastek/95b2c605b29e9a401c6d to your computer and use it in GitHub Desktop.
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
| /** | |
| * [Directive] apply styles according to current window width | |
| * @example | |
| * | |
| * <div media-style="{ '768': 'background: red;', '1024': 'background: blue;' }"></div> | |
| */ | |
| angular.module('app') | |
| .directive('mediaStyle', ['$window', '$timeout', | |
| function($window, $timeout) { | |
| var link = function($scope, $el, $attrs) { | |
| // helpers | |
| var timer = null; | |
| var styles; | |
| var breakpoints; | |
| // if there is no media-style attribute or provided styles | |
| // ar not object, disable directive | |
| if (!$scope.mediaStyle && !angular.isObject($scope.mediaStyle)) { | |
| return false; | |
| } | |
| styles = $scope.mediaStyle; | |
| // get styles properties and return them as Array | |
| // then sort them descending | |
| breakpoints = Object.keys(styles).map(function(key) { | |
| return Number(key); | |
| }); | |
| breakpoints.sort(function(a, b) { return b - a; }); | |
| angular.element($window).on('load resize', function(event) { | |
| var w = $(this); | |
| // debounce $window resize | |
| $timeout.cancel(timer); | |
| $timeout(function() { | |
| for (var i = 0; i < breakpoints.length; i++) { | |
| // if current window width is greater than certain resolution | |
| // apply styles | |
| // for other breakpoints, that are also greater than current | |
| // window width, break loop to prevent overriding styles | |
| if (w.width() >= breakpoints[i]) { | |
| $el.attr('style', styles[ String(breakpoints[i]) ]); | |
| break; | |
| } else { | |
| $el.attr('style', ''); | |
| } | |
| } | |
| }, (event.type === 'load') ? 0 : 300); | |
| }); | |
| }; | |
| return { | |
| scope: { | |
| mediaStyle: '=' | |
| }, | |
| restrict: 'A', | |
| link: link | |
| }; | |
| } | |
| ]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment