Skip to content

Instantly share code, notes, and snippets.

@punmechanic
Last active August 29, 2015 14:16
Show Gist options
  • Save punmechanic/7984d394b11ea0beed67 to your computer and use it in GitHub Desktop.
Save punmechanic/7984d394b11ea0beed67 to your computer and use it in GitHub Desktop.
Responsiveness in Angular. This could be done in pure CSS, but I had a brain fart.
<responsive>
<div ng-switch='screenSize'>
<div ng-switch-when='small'>
<h1>Small Screen</h1>
</div>
<div ng-switch-when='medium'>
<h1>Medium Screen</h1>
</div>
<div ng-switch-when='large'>
<h1>Large Screen</h1>
</div>
</div>
</responsive>
angular.module('app', [])
.constant('screenSizes', [
{'name': 'small', 'width': 320},
{'name': 'medium', 'width': 640},
{'name': 'large', 'width': 960}
])
.service('ScreenSizeService', function(screenSizes) {
// TODO find a way to sort array, but not in place.
// Sort screen sizes in order of smallest to largest
screenSizes.sort(function(a, b) {
if(a.width === b.width) return 0;
return a.width < b.width ? -1 : 1;
});
this.size = function(widthPx) {
for(var idx in screenSizes) {
var screenSize = screenSizes[idx];
// if the current screen size is larger than our
// screen size, then we should return here (as this is the
// smallest size because we ordered the screenSizes array)
if(screenSize.width >= widthPx)
return screenSize.name;
}
// If we reach here and we have not returned, then the width
// is very large indeed. in this case, we should just return the
// last element of screenSizes.
return screenSizes[screenSizes.length - 1].name;
};
})
.directive('responsive', function($window, ScreenSizeService) {
return {
restrict: 'E',
controller: function($scope) {
var that = this;
that.resize = function(newWidth) {
that.size = ScreenSizeService.size(newWidth);
};
},
controllerAs: 'responsive',
link: function($scope) {
var window = angular.element($window);
window.on('resize', function() {
$scope.responsive.resize($window.outerWidth);
// This event comes from outside of angular's event loop,
// so force an apply
$scope.$apply();
});
// immediately trigger so we can get an initial size
$scope.responsive.resize($window.outerWidth);
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment