I am currently working on the following:
http://jsbin.com/EDovILI/1/edit
Essentially, I am inserting an event listener into the controller. It doesn't feel like the most efficient way to do it, but I'm not sure how to abstract it out.
The template:
<div ng-app="app" ng-controller="appController">
<div ng-if="layout == 'big'>...</div>
<div ng-if="layout == 'small'>...</div>
</div>
The JavaScript:
function gitReposController($scope, github){
//...
var widthQuery = window.matchMedia("(min-width: 44.375em)");
var setSizeAppropriateTemplate = function (mql) {
if (mql.matches) {
$scope.layout = 'big';
} else {
$scope.layout = 'small';
}
if(!$scope.$$phase) { //prevents it from unnecessarily calling $scope.$apply when the page first runs
$scope.$apply();
}
};
widthQuery.addListener(setSizeAppropriateTemplate);
setSizeAppropriateTemplate(widthQuery);
//...
}
edit/addendum:
Is it considered bad practice to create an event listener in the controller? Should it be a Directive instead? Or perhaps a Behavior?
edit: I modified it into a directive and now it makes more sense. However, there may be room for improvement.
http://jsbin.com/EDovILI/4/edit
The template:
<div ng-app="gitRepos" ng-controller="gitReposController" breakpoint="min-width: 44.375em">
<div ng-if="matches">...</div>
<div ng-if="!matches'>...</div>
</div>
The JavaScript
app.directive("breakpoint", function () {
return function (scope, element, attrs) {
var breakpoint = attrs.breakpoint;
var mql = window.matchMedia( "(" + breakpoint + ")" );
var mqlHandler = function (mql) {
scope.matches = mql.matches;
if(!scope.$$phase) { //prevents it from unnecessarily calling $scope.$apply when the page first runs
scope.$apply();
}
};
mql.addListener(mqlHandler);
mqlHandler(mql);
};
});