Skip to content

Instantly share code, notes, and snippets.

@egermano
Last active December 15, 2017 01:59
Show Gist options
  • Save egermano/7451739 to your computer and use it in GitHub Desktop.
Save egermano/7451739 to your computer and use it in GitHub Desktop.
Align Directive for AngularJS

Align

Align a element base on multiples values, like a, top, bottom, middle, right, left and center.

Usage

<div class="recipes clearfix" align="middle center" align-watch="recipes">
    ...
</div>

<div class="recipes clearfix" align="top center" align-watch="recipes">
    ...
</div>

align attribute deifne the rules to aline the element

align-watch attibute define a variable to watch to run the directive again, when that value has changed

angular.module('app')
.directive('align',function($timeout){
'use strict';
var linker = function(scope, element, attrs) {
var options = attrs['align'].split(" "),
listner = attrs['alignWatch'];
var positioner = function(){
angular.forEach(options, function(value, key){
element.css('position', 'absolute');
switch (value) {
case 'top':
element.css({
top: '0',
marginTop: '0'
});
break;
case 'bottom':
element.css({
bottom: '0',
marginBottom: '0'
});
break;
case 'middle':
element.css({
top: '50%',
marginTop: ((element.height()/2) * -1) + 'px'
});
break;
case 'right':
element.css({
right: '0',
marginRight: '0'
});
break;
case 'left':
element.css({
left: '0',
marginLeft: '0'
});
break;
case 'center':
element.css({
left: '50%',
marginLeft: ((element.width()/2) * -1) + 'px'
});
break;
}
});
}
$(window).resize(function(){
positioner();
});
if (listner) {
scope.$watch(listner, function(){
positioner();
});
};
$timeout(function(){
positioner();
});
};
return {
restrict:'A',
link: linker
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment