Is the "Angular" approach to creating responsive templates? Should matchMedia be used in the 'controller'?

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);
    };
});

Answer №1

Exploring the possibility of incorporating this functionality into my Angular projects has piqued my interest, and I've come across a few potential solutions that could benefit us both:

Although I have not extensively tested any of these methods, it appears that these developers shared our same line of thinking. Hopefully, this information proves beneficial to both of us!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The proxy URL is not functioning properly within the Angular JS controller

Currently, I am in the process of developing an application using expressjs and angularjs. To set up my backend, I utilized the express generator to install essential tools such as mysql, body parser, and cors. For the frontend, I integrated gulp with an ...

Issue encountered during app creation using the command line interface

After successfully installing nodejs and checking the versions of nodejs, npm, and npx, I proceeded to run the command npm install -g create-react-app which executed without any issues. However, when I attempted to create a new React app using create-react ...

Is it possible to encase <v-img> within an anchor element?

I am currently using Vuetify 1.5 and have included a couple of <v-avatars></v-avatars> elements in which there is a nested <v-img></v-img>. I attempted to enclose the img tags within an a tag but encountered an issue wherein the ima ...

Ways to showcase numerous records in Ember.js template using hasMany relationship?

The model I have defined looks something like this: App.Question = DS.Model.extend({ title: DS.attr( 'string' ), answers: DS.hasMany('App.Answer') }); App.Answer = DS.Model.extend({ title: DS.attr( 'string&ap ...

Loading data with React Router every time

I'm still getting the hang of React and React Router. On the home page (home component), data is loaded from the server via an AJAX request to display the information. However, when users navigate within the app using React Router and return to the ...

Inside the function() in angular 2, the value of 'this' is not defined

I've integrated a UIkit confirmation modal into my app. However, I'm encountering an issue when trying to click the <button> for confirmation. The this inside the function is showing up as undefined. Here's the snippet of code in quest ...

Universal - Permissible data types for function and constructor arguments

In many statically typed languages, it is common to specify a single type for a function or constructor parameter. For example: function greet(name: string) { ... } greet("Alice") // works greet(42) // error TypeScript is an extension of JavaScri ...

AngularJs - Customizable dynamic tabs that automatically adapt

Below is the HTML code snippet: <div> <ul data-ng-repeat ="tab in tabs"> <li data-ng-class="{active: tab.selected == 'true'}" message-key="Tab"> </li> </ul> </div> As shown ...

How should the folder structure be set up for dynamic nested routes in Next.js?

I've been reviewing the documentation for Next.js and believe I grasp the concept of dynamic routing using [slug].js, but I am facing difficulty understanding nested dynamic routes in terms of folder organization. If I intend to develop an applicatio ...

Does the resolve function within a Promise executor support async operations?

I'm trying to wrap my head around the following code: function myPromiseFunc() { return new Promise((resolve) => { resolve(Promise.resolve(123)); }); } We all know that the Promise.resolve method immediately resolves a Promise with a plain ...

Guide on how to navigate to a different page upon logging in with react-router-dom V5

I have implemented routing in my create-react-app using react-router-dom version 5.2.0. My goal is to use react-router for redirects and route protection within the application. The initial landing page is located at /, which includes the login/signup fun ...

Resizing svg to accommodate a circle shape

As I work on my vue.js app that involves a plethora of diverse icons, I made the decision to create a small icons builder in node.js. The purpose is to standardize their usage and also "crop" each SVG so it fits perfectly within its parent container by uti ...

Is there a way to identify a visitor's country and automatically direct them to a relevant website?

Despite reading multiple answers, I am still unsure how to redirect my website's visitors based on their country. I have a basic understanding of HTML and JavaScript. Can someone kindly provide me with the code for this task? ...

Is there a way to input data into an AngularJS modal?

I'm looking for some assistance : How do I go about loading data into the content of an angular modal? Is there a way to load custom data for a selected item? ............................................................. This is the code ...

What steps are involved in creating a video playlist with YouTube videos?

Is there a way to create a dynamic video playlist that supports embedded YouTube videos without refreshing the page? If a user clicks on another video, I want the video to change dynamically. You can check out this for an example. Do jPlayer, Video.js, Fl ...

What is the best way to create a slideshow using an IFrame?

Currently seeking a solution for an iframe slideshow that can smoothly transition between multiple HTML iframes. I have a total of 5 iframes that need to rotate automatically and continuously. Any suggestions on how to build a lively and dynamic iframe sl ...

transferring information within React applications

I created a basic online store and I am looking to transfer data from one JavaScript file to another. The first JS file displays the items, and then I want to pass the item data to cart.js which contains a table. <section className="products"> ...

The store for WrappedApp was just initialized using withRedux(MyApp) { initialState: undefined, initialStateFromGSPorGSSR: undefined }

I am trying to create multiple routes with express and next.js. After running npm run export, I encountered the following message: next export info - using build directory: C:_PROJECT.next info - Copying "static build" directory info - Launching 3 wor ...

The functionality of minified JS code is limited to being copied and pasted directly into the

Trying to explain the issue I'm facing may be a bit tricky, but here it goes: I've been working on an AngularJS app (not live yet) and we felt the need to add tooltips for specific metrics in our tables. After some research, we really liked the ...

waiting for elements in Nightwatch.js using FluentWait

I am seeking assistance on implementing FluentWait using nightwatch.js. How can I achieve this? Within my project, I have a global.js file that includes: waitForConditionPollInterval : 300, waitForConditionTimeout : 5000, However, it seems like this ...