angular.module('AngTestApp')
.directive('respDiv', function ($window)
{
return {
// replace the element with the template below
replace: true,
// uses ng-include to bind the contents to the
// breakpoints
template: '<div ng-include="template"></div>',
// new isolate scope
scope: {},
link: function postLink(scope, element, attrs)
{
// we'll use this function to determine which
// breakpoint we are currently within
function checkBreaks(width){
// start with window width so we have
// a default value, if it is not within
// a breakpoint
var curBreak = $window.innerWidth;
// start with the default template
var template = attrs.respDiv;
// are we withing the small breakpoint?
if(attrs.smallbreak && width < attrs.smallbreak){
curBreak = attrs.smallbreak;
template = attrs.smalltemplate;
}
// are we within the medium breakpoint?
else if(attrs.medbreak && width < attrs.medbreak){
curBreak = attrs.medbreak;
template = attrs.medtemplate
}
// check if update necessary (i.e. break dif)
if(curBreak != scope.break){
scope.break = curBreak;
// this is the real key, we change the
// value of the template, which the
// ng-include directive used in this
// component's template will use to
// fetch it's contents
scope.template = template;
}
};
// check initial size
checkBreaks(element[0].clientWidth);
// TODO: could not figure out how to bind to the
// element's resize events, so using window for now...
$window.onresize = function()
{
// since we're inside a DOM event, we need to use
// $apply to re-enter Angular world
scope.$apply(function(){checkBreaks(element[0].clientWidth)});
};
}
};
});