Skip to content

Instantly share code, notes, and snippets.

@mciastek
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save mciastek/95b2c605b29e9a401c6d to your computer and use it in GitHub Desktop.

Select an option

Save mciastek/95b2c605b29e9a401c6d to your computer and use it in GitHub Desktop.
/**
* [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