Responsive template swapping with Angular Directives

I've posted a few days ago on responsive template swapping with Backbone, here's an example showing how to do that in Angular using a custom Directive.

See the Pen hfAxn by Chang Wang (@cheapsteak) on CodePen

The custom breakpoint directive takes a media-query as an argument (in this case min-width: 44.375em) and creates a MediaQueryList mql and a MediaQueryListListener mqlListener, which will update our custom scope variable matches so it will always reflect the result of the media-query (in our case, scope.matches will be false when width is smaller than 44.375em and true when width is larger).

Since the media-query event that triggers the change to the scope variable matches is not generated by Angular, we will need to update our view by calling scope.$apply() to manually start the digest cycle. However, since page-load doesn't trigger media-query events, and since we still want the right layout to be displayed on page-load, we also need to make a direct call to mqlListener(mql) during the directive's initialization, which is during an existing digest cycle. Calling scope.$apply() then would result in an Action Alredy In Progress error, so we check scope.$$phase and only call scope.$apply when not in an existing digest cycle. Hence the weird looking:

if(!scope.$$phase) { // make sure we're not in the middle of a digest cycle
    scope.$apply(); //start the digest cycle
}

This and the Backbone example are available on GitHub. Shoot me a pull request or a tweet and let me know what you think!