I have created this directive in Angular. The idea is to calculate width of height and height of specific element via style function attached to ng-style on the same element.
The directive uses underscore for debounce, and $routeScope
to receive called from the element, $window
to get full height and width of it.
How can I improve this code to make it more testable, more readable?
(function (ng, _) {
ng.module('mixbank.app').directive('tableResize', [
'$window',
'$rootScope',
function ($window, $rootScope) {
return function (scope, element, attrs) {
var w = ng.element($window);
var topOffsetCalculate = function () {
return {
total: ng.element("nav.navbar-fixed-top").height() +
ng.element("nav.navbar-business").height() +
ng.element(".table-business-rules thead").height()
}
};
var topOffset = topOffsetCalculate().total;
var leftOffset = ng.element(".left-business-rules-view").outerWidth();
var rowHeight = 58;
var expandedRowHeight = 175;
scope.getWindowDimensions = function () {
return {
'h': w.height(),
'w': w.width(),
'th': attrs.totalRows * rowHeight + topOffset
};
};
function doLayout(expandedRule) {
var newValue = scope.getWindowDimensions();
var possibleHeight = expandedRule ? newValue.th + expandedRowHeight : newValue.th;
scope.style = function () {
var h = Math.min(possibleHeight, newValue.h);
return {
height: (h - topOffset) + 'px',
width: (newValue.w - leftOffset) + 'px'
}
};
}
var resizeHandler = _.debounce(function () {
doLayout();
scope.$apply();
}, 300);
$rootScope.$on('expandRow', function (event, data) {
typeof data != 'undefined' ? doLayout(true) : doLayout();
});
scope.$watch(function () {
return attrs.totalRows;
}, function () {
doLayout();
});
scope.$on('$destroy', function () {
w.off('resize', resizeHandler);
});
w.on('resize', resizeHandler);
}
}
])
;}(window.angular, _));