I'm trying to use an Angular JS directive to center the contents of a div.
This is the simplified version of the template:
<div id="mosaic" class="span12 clearfix" s-center-content>
<div ng-repeat="item in hits" id="{{item._id}}" >
</div>
</div>
This is the directive:
module.directive('sCenterContent', function() {
var refresh = function(element){
var aWidth= element.innerWidth();
var cWidth= element.children()[0].offsetWidth;
var cHeight= element.children()[0].offsetHeight;
var perRow= Math.floor(aWidth/cWidth);
var margin=(aWidth-perRow*cWidth)/2;
if(perRow==0){
perRow=1;
}
var top=0;
element.children().each(function(index, child){
$(child).css('margin-left','0px');
if((index % perRow)==0){
$(child).css('margin-left',margin+'px');
}
});
};
return {
link : function(scope, element, attrs) {
$(window).resize(function(event){
refresh(element);
});
}
};
});
It basically floats some inner divs and adds a margin to the first div in each row, so the content is centered.
This works fine when the browser is resized. The problem comes when I try to do a refresh just after initialization.
I have tried with the post linking function as seen in this question. The pre link and post link functions get called in the expected order but not after the children of the elemenet with the s-center-content directive get rendered. The call to refresh fails as no children are found.
How can I make a call to refresh ensureing the children have been processed?