Updating AngularJS views based on window resizing

I've been working on an Angularjs application and everything is running smoothly, but I'm facing challenges when it comes to implementing a mobile version of the site. Simply using responsive styles won't cut it; I need to use different view files for the mobile and desktop versions. In my app, I'm utilizing ui-router with the following configuration:

dopGruz
    .config([ '$stateProvider', '$urlRouterProvider','$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider){
    $stateProvider
        .state('root',{
            views: {
                "navbar" : {
                    controller: 'viewsController',
                    templateProvider: function($http, viewsWatcherFactory) {
                        return viewsWatcherFactory
                            .get('app/views/nav-bar.html')
                            .then(function(obj){
                                return $http
                                    .get(obj.templateName)
                                    .then(function(tpl){
                                        return tpl.data;
                                    });
                            });
                } },
                "" : { template: '<div ui-view></div>' }
            }
        })

My factory returns a mobile template based on window width:

dopGruz.factory('viewsWatcherFactory', [
    '$http',
    '$timeout',
    function($http, $timeout) {

        var _ifMobile = (function(){
            return window.innerWidth < 850;
        })();

        return {
            get : function(id) {
                return $timeout(function(){
                    var path = id;
                    if (_ifMobile) {
                        path = id.split('/');
                        path.splice(path.length-1,0,'mobile');
                    }
                    if (Array.isArray(path)) {
                        path = path.join('/');
                    }
                    return {templateName : path};
                }, 0);
            }
        };
    }
]);

While this setup works well on page load by loading the mobile version of the template if the window width is less than 850px, I'm looking for a way to manually call the templateProvider based on an event. I have a controller where I would like to implement this:

dopGruz.controller('viewsController', function ($scope,$window) {

    angular.element($window).bind('resize', function() {
        console.log($window.innerWidth);
        // Implement logic to call templateProvider and update views files.
        $scope.$digest();
    });

});

If there's a simpler or more efficient way to achieve this, any guidance would be greatly appreciated.

Answer №1

To switch between mobile and desktop versions of a template, I recommend using ng-include in AngularJS. This involves setting the src attribute to a scope variable that points to the desired template. While the example provided here may not cover all scenarios, it should give you a good idea of how to implement this feature.

Controller:

app.controller('MainCtrl', function($scope) {
$scope.templates =
[ { name: 'mobile.html', url: 'mobile.html'},
  { name: 'desktop.html', url: 'desktop.html'} ];
$scope.template = $scope.templates[0];
});

Main template:

<body ng-controller="MainCtrl">
   <ng-include class="col-md-12" src="template.url"></ng-include>
</body>

Mobile template:

<div>mobile template</div>

Desktop template:

<div>desktop template</div>

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

Issues with ng-show functionality occurring during the initialization of the webpage

While working on a webpage using HTML, CSS, and Angular.js, I encountered an issue where the page content would not display properly upon loading. The objective was to show selected content based on user choices from a dropdown menu. Although the filtering ...

Using recursive setTimeout in Javascript may not always utilize the entire final JSON object that is returned

My current approach involves making recursive calls to a URL until it returns either a success or reaches the maximum limit of tries. Below is a compact version of the relevant code: function doSomething(numRetries) { $.post('someURL', {retr ...

What is the best way to choose the unique identifier of an HTML element inside a for loop in a Django template?

I need help selecting an HTML button that is generated within a for loop in a Django template using JavaScript. How can I assign a unique ID to each button and select it correctly in JavaScript? Currently, all buttons have the same ID within the loop, resu ...

Effective communication among sibling components in Vue.js

Interaction between parent and child components can be easily achieved using $broadcast and $dispatch However, I'm currently faced with a challenge regarding communication between sibling components. My current approach involves triggering a $dispatc ...

Extract the label from Chip component within the onClick() event in material-ui

-- Using Material-UI with React and Redux -- Within my material-ui table, there are <TableRow> elements each containing multiple <TableCell> components with <Chip> elements. These <Chip> components display text via their label prop ...

Having trouble changing the chosen selection in the material UI dropdown menu

I've encountered an issue with my material ui code for a select dropdown. It seems that the selected option is not updating properly within the dropdown. <FormControl variant="outlined" className={classes.formControl}> <InputLabel ref={ ...

Adding elements to an array appears to cause the previously created object to react

I am encountering a situation where once I add an object to an array, it becomes reactive to any changes made. // actions.js export const addToCart = ({ commit }) => { commit('addToCart'); // successfully updates the state setTimeout ...

What is the best way to incorporate JQuery into html content retrieved through an ajax request?

In my jsp file, there is a div structured like this : <div id="response" class="response"></div> After triggering an ajax call to a servlet, the content of this div gets updated with the following elements : <div id="response" class="res ...

"Upon populating an object with Mongoose, the return value is an

Recently, I set up a mongo database and created a Post model that has a reference to the User by _id. I wanted to retrieve information about the posts a user has made, so I implemented a callback function within exec() while populating the selected User. H ...

Manipulating state in React

Currently, I am enrolled in Samer Buna's Lynda course titled "Full-Stack JavaScript Development: MongoDB, Node and React." While working on the "Naming Contests" application, I encountered a piece of code within the App component that has left me puzz ...

Displaying information in ejs format

I am currently working on a project to develop a basic webpage that requires the user to input a specific time and then click on submit. Once submitted, I want the relevant data linked to that input to be displayed on the webpage. Upon clicking the submit ...

Tips for managing the response from a POST request using jQuery

I'm currently working on sending data via POST to my ASP.Net MVC Web API controller and retrieving it in the response. Below is the script I have for the post: $('#recordUser').click(function () { $.ajax({ type: 'POST', ...

Error code -4058 ENOENT indicates that the file or directory does not exist. This issue is usually caused when npm is unable to locate a specific file

Trying to start a react project on my D: drive while having node installed on the C: drive resulted in an error: D:\react> npm start npm ERR! code ENOENT npm ERR! syscall open npm ERR! path D:\react/package.json npm ERR! errno -4058 npm ERR! ...

Unable to save Ajax data in session array

Currently, I am developing a cart system using jquery, ajax, and php. The issue I am facing is that the text within the HTML elements is not being added to the session array. Below is the ajax code I am using: $(document).ready(function(){ $("#car ...

I'm encountering an error when trying to use makeStyles

Something seems off with MUI. I was working on my project yesterday and makeStyles was functioning properly, but now it's suddenly stopped working. I'm encountering an error when calling it here: I suspect the issue lies in the import statement ...

Navigate through each of the pictures within the folder and encode them into base64

I'm currently working on a project where I need to convert images in a folder to base64 and then store them in MongoDB. At first, I successfully converted a single image: var filename = '1500.jpg'; var binarydata = fs.readFileSync(filename ...

Insert a JSX element into the body of a webpage using React JSX

Is there a way to dynamically add elements to the end of the body using vanilla JavaScript? const newRecipe = <div id = "container"> <div className="recipe App" id="four" onClick={this.toggleRecipeList.bind(this)}>{this.state.recipeName} < ...

Is there a way to utilize OpenLayers to showcase various icons for distinct features all within one layer?

Being new to Openlayers/JS and fairly inexperienced with programming in general, there may be other issues in my code that I'm unaware of. I am currently using the latest version of Openlayers (5.3.0). My application sends GeoJson formatted data via ...

Is it feasible to maintain a variable as a reference across views while utilizing ng-view?

I am facing a unique challenge: I have a webpage with two tabs that need to utilize ng-view from AngularJS. The twist is that both tabs must share the same variable, similar to referencing a variable in C# using the "ref" keyword. If you want to see an ex ...

Is NextJS rendering solely on the server, or is it capable of rendering on both

Within my users.js JSX file, I have an exported component that looks like this: ... return <MainContainer keywords="users"> export default Users During the process of SSR/SSG, the browser displays the users HTML (comprising of <li> t ...