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

What is the best way for me to show comments beneath all of my posts?

Currently, I am facing an issue with my application where I need to retrieve comments from posts. I am unsure of the best approach to tackle this problem. The existing system only displays posts that have comments, but it shows only a single comment inste ...

The DataTable is encountering difficulties with processing JSON data retrieved from the database

Setting up a datatable on my website has been quite the challenge. I came across a table that I wanted to use here, but converting it to fit my needs has not been successful. Currently, the table is not populating with rows from a database table and I&apos ...

Guide to displaying the output of a JS calculation in a Bootstrap modal dialog box

I have a HTML and JavaScript code that determines the ideal surfboard for the user based on their input data (style, experience, height, weight) and displays the recommended surfboard type. Here is the initial code snippet I attempted to use: function c ...

Using VueJS to apply filters to an object causes a decrease in my application's performance

Recently, I've been working on implementing a filter for a search bar. However, I've noticed that whenever I input something into the search bar, there is a noticeable delay as it loads the entries. I'm not sure if this issue is related to ...

What is the best method to remove a value from a JSON object in a CSV file?

I received a JSON response like this: xxx: ["fsd,das"] I am looking for a way to remove the value "fsd" from the JSON object. The issue is that the response inside the JSON is not actually an array, but rather a CSV format. How can I go about deleting it ...

What could be causing axios to not function properly when used with async/await in this particular scenario

I need to update the DoorState when a button is clicked. After sending a request to the API to change the DoorState, I then call another API to check the status of the robot. Even though the DoorState has been successfully changed, it seems that the chan ...

Oops! Looks like there's an issue with the type error: value.forEach is

I am working on creating an update form in Angular 6 using FormArray. Below is the code snippet I have in editfrom.TS : // Initialising FormArray valueIngrident = new FormArray([]); constructor(private brandService: BrandService, private PValueInfoSe ...

Implementing Alloy-Script/Javascript in dynamically loaded JSP files

I have been loading various JSPs dynamically using an Ajax call, but after the JSP is loaded, none of the JavaScript inside seems to be working. I suspect this is because the script has not been parsed yet. To address this issue, I came across the "aui-pa ...

Are there any factors within a local network or desktop environment that may impact the execution of JScript?

Something strange is happening with the JavaScript on my project. It works perfectly fine, except when accessed from computers at a specific company. Even more puzzling is that the JavaScript only fails about half of the time when accessed from that compan ...

Intercepting HTTP requests on specific routes with Angular 4+ using an HTTP Interceptor

I've developed an HTTP_INTERCEPTOR that needs to function on certain routes while excluding others. Initially, it was included in the main app module file. However, after removing it from there and adding it to specific modules, the interceptor conti ...

Retrieving values from nested arrays in Vue.js

I'm currently delving into Vue3. My goal is to extract the values from an array within an array in order to create a neat table. Once extracted, I plan to separate these values with commas. For more information, you can visit this link: https://stack ...

Tips for creating a unique scroll page arrow button with adjustable thickness?

Seeking guidance on how to adjust the thickness of the arrow used as a scroll button on my website. I am aiming for a similar look to the arrow on this particular website: example of arrow To view my code, please visit: Codepen .next { position:absolut ...

Using an external function to implement Javascript and AJAX interactions

function makeAjaxRequest(destination_full_url) { if (window.XMLHttpRequest) {// code for modern browsers xmlhttp = new XMLHttpRequest(); } else {// code for old Internet Explorer versions xmlhttp = new ActiveXObject("Microsoft.XMLH ...

Tips for associating an id with PrimeNg menu command

Within my table, I have a list of items that I would like to enhance using PrimeNg Menu for dropdown menu options. The goal is to enable navigation to other pages based on the selected item id. When a user clicks on a menu item, I want to bind the id of th ...

Using the React Hook useCallback with no dependencies

Is it beneficial to utilize useCallback without dependencies for straightforward event handlers? Take, for instance: const MyComponent = React.memo(() => { const handleClick = useCallback(() => { console.log('clicked'); }, []); ...

Tips for passing navigator reference to React Native's <Drawer/> component?

Utilizing react-native-drawer ( https://github.com/root-two/react-native-drawer ) in my index.ios.js file, I have the following setup where I am attempting to pass the 'navigator' reference into the <DrawerPanel /> of <Drawer /> compo ...

Exploring VueJs 3's Composition API with Jest: Testing the emission of input component events

I need help testing the event emitting functionality of a VueJs 3 input component. Below is my current code: TextInput <template> <input v-model="input" /> </template> <script> import { watch } from '@vue/composition-api&ap ...

ESLint only lints certain errors in the command-line interface

Incorporating eslint into my project has been a game-changer. Here's how my .eslintrc file is set up: // http://eslint.org/docs/rules { "parser": "babel-eslint", "env": { "browser": true, "node": true, "mocha": true }, "plugins": ...

What are the methods for altering the material of a glTF model using THREE.js?

I've created a model using Blender and baked all the lighting and textures. However, when I import it into THREE.js in .glb format, it automatically uses the standard material. While this may work in certain cases, my concern is that I want to retain ...

Tips for integrating JavaScript code into React JS applications

I am attempting to create a scrollable table that scrolls both horizontally and vertically, using the example provided by . In my project directory under src/components/ScrollExample.js, I have copied and pasted the HTML code. In addition, in src/styles/c ...