Struggling to upgrade dynamic routes from AngularJS version 1.2 to 1.6

Having successfully implemented code for dynamically loading routes and controllers in AngularJS 1.2, I now face issues after upgrading to AngularJS 1.6 as the dynamics no longer function.

The previous code was used to load JS files and recalculate the route:

moduleApp.config(function ($routeProvider, $controllerProvider) {
    moduleApp.controllerProvider = $controllerProvider.register;
    moduleApp.routeProvider = $routeProvider;

    $routeProvider.when('/', {
        templateUrl: 'startpage.html',
        controller: 'startpageController'
    })
    .otherwise({
        resolve: {
            deps: function($q, $rootScope, $location) {
                var deferred = $q.defer();

                var modulename = $location.path().split("/")[1];

                if (modulename !== null) {
                    // Using https://github.com/ded/script.js to load JS files
                    $script(modulename + ".js", function() {
                        $rootScope.$apply(function() {
                            $rootScope.$broadcast('$locationChangeSuccess', $location.path(), $location.path());
                        });
                    });
                }

                return deferred.promise;
            }
        }
    });
});

This is how the loaded JS file appears:

moduleApp.routeProvider.
    when('/FirstModule', {
        templateUrl: 'FirstModule.html',
        caseInsensitiveMatch: true
    });

moduleApp.controllerProvider('firstModuleController', function ($scope) {
});

In AngularJS 1.2, this method functions perfectly fine. However, it seems that applying the route in 1.6 differs. What modifications should be made within the function utilizing $rootScope to make it work again? Are there any other adjustments required?

A demonstration of this situation is available on Plunker.

To observe functionality in AngularJS version 1.2.16, change to the respective setting in index.html and adjust hashbangs in links from #! to #. Switching back to version 1.6 reveals the issue with the current setup.

Answer №1

That statement seems a bit unusual. It was causing you to get stuck in an infinite loop.

$rootScope.$broadcast('$locationChangeSuccess', $location.path(), $location.path());

Instead of attempting to deceive Angular into reloading, just utilize $route.reload()

.otherwise({
    resolve: {
        deps: function($q, $rootScope, $location, $http, $route) {
            var deferred = $q.defer();

            var modulename = $location.path().split("/")[1];

            if (modulename !== null) {
                $script(modulename + ".js", function() {
                    $rootScope.$apply(function() {
                        //$rootScope.$broadcast('$locationChangeSuccess', $location.path(), $location.path());
                        $route.reload();
                    });
                });
            }

            return deferred.promise;
        }
    }
});

Check out the working Plunker

In addition, there was a slight issue. Missing parenthesis in ng-click="FirstButton"

 

Edit based on comment:

Broadcasting system events ($locationChangeSuccess) as you were doing can be risky. You were somewhat fortunate that it worked in 1.2, as it wasn't officially supported. The location change was not a success, despite what your code suggests.

The documentation for reload simply states:

Causes $route service to reload the current route even if $location hasn't changed. As a result, ngView creates a new scope and reinstantiates the controller.

Therefore, this approach should work in all supported versions. I don't foresee any negative consequences. It's essentially the standard method of achieving what you were trying to accomplish with your custom solution.

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 image spills over with abundance

I'm currently working on creating a movie watchlist interface, but I'm facing challenges with maintaining the design consistency. I am utilizing the tmdb API to retrieve movie information. My goal is to have each section resemble the first one (H ...

Encountered an error stating 'Cannot read property 'user' of undefined' while attempting to generate a user document during account creation using Firebase

I'm having trouble adding the user ID to a new collection named 'accounts' during account creation. I keep encountering an error that says 'Cannot read property 'user' of undefined'. Can someone please help me troubleshoo ...

Ways to determine if the user is either closing the browser or navigating to a different website

I am looking to set up session management in a manner where all sessions are expired or destroyed when the user closes the browser or tab. However, I would like to retain all the sessions if the user is navigating to another website. Is there a way to ac ...

Setting up a NodeJS project (built with Express and Angular) on a Ubuntu Cloud Server with NGINX hosting

I have a domain and a cloud server (running Ubuntu 16.04 OS), and I am attempting to host a nodeJS project (using ExpressJS and AngularJS) on the cloud server. Currently, I have installed Node.js and Nginx on my cloud server. My application is running loc ...

Attempting to retrieve an item from a JSON array of objects results in the value of "Undefined"

I am currently working with a Blockspring API that pulls data from a Google Sheet in the form of a JSON array. However, I am encountering an issue where I receive an "undefined" value when trying to access an object within the array. I have included both t ...

Guide on positioning a 3D model to face forward in the direction of its movement

I'm just starting to learn about 3D graphics, so a lot of the terminology is unfamiliar to me... In my ThreeJs project, I have a 3D model flying around a room and avoiding walls. When it gets near a wall, it needs to turn slightly to avoid hitting it ...

How can I navigate to a specific div within a nested div using JavaScript?

Is there a way to make the window scroll up to a specific div (temp-class) when I click a button? The code I've tried doesn't seem to work, possibly due to CSS styles that cannot be removed. Here is the snippet of my code: <body> <div c ...

Tips for including multiple plugins in a next.config.js

I am eager to introduce sass and BEM methodology into our company's project, but I am encountering some challenges with integrating the sass plugin into our existing codebase. Currently, we are utilizing typescript and CSS plugins. const path = requi ...

Limit the number of Twitter Bootstrap popup tooltips to one using Jquery, ensuring only one instance of the popup is displayed at

Here is some HTML code that I am working with: <table class="bag"> <tr> <td id='slot0' item-type="" item-id=""> <a href="#" id="tool1" rel="popover" data-content="cont" data-original-title="ti-ta" da ...

Navigate using jquery on a keyboard starting from a designated input text field

I'm currently developing an internal web application and I want to incorporate keyboard navigation into it. After doing some research, it looks like using JavaScript is the most effective way to achieve this. Below is a snippet of what I have come up ...

JavaScript Date behaving oddly

While working with Javascript, I encountered a puzzling issue involving the Date object. date1 = new Date(1970, 1, 1); date2 = new Date("1970-01-01T13:00:00.000Z"); console.log(date1.getYear()); //70 console.log(date1.getMonth()); //1 console.log(date1.g ...

Issue with printing data consecutively using Javascript

My JavaScript code aims to display the content of the body tag again when the add button is clicked. The purpose is to add authors, with each author being added in sequence. For example, if there is only 1 author present, the user simply selects whether th ...

Vue not displaying local images

I'm having trouble creating an image gallery with Vue.js because local images are not loading. I have the src attributes set in the data attribute and can only load images from external sources. For example: data() { return { imag ...

The onClick event handler is triggered on page load instead of waiting for a click

Recently delving into React, I encountered an issue while attempting to call a function set as a prop. Take a look at my component below: class SamplesInnerLrg extends Component { playSampleAction(sample,sampleId) { console.log(sample); } ...

Unable to input text using Python Selenium in a textbox

Currently, I am attempting to input text into a specific textarea HTML element using Python Selenium: <div class="spk-c spH-d"><div id="gwt-uid-23" class="sppb-a"> <div class="sppb-b spk-b">For example, flowers or used cars</div> & ...

Troubleshooting: The issue of Vue (v-on) not recognizing my function

I am brand new to Vue and JS, so please bear with me as I ask some "silly" questions. Within my Vue-Pet-Project, I have implemented a self-authored class module called Sudoku. In this module, I aim to find solutions using backtracking. Upon clicking the " ...

When `rxjs` repeat and async pipe are applied and then removed from the DOM, the resulting value becomes null

One of the classes I have is responsible for managing a timer. It contains an observable that looks like this: merge( this._start$, this._pause$ ) .pipe( switchMap(val => (val ? interval(1000) : EMPTY)), map( ...

transferring double quotation marks and square brackets through a parameter

I have an angularjs (1.x) scope set up as follows: $scope.report = { resource: '/public/emplyACH', params: { "employeeId": [78] } }; When I try to access it using console.log (console.log(scope.parms)) I see the output as ...

Retrieving information from Firebase after updating it

My goal is to automatically navigate to a specific ID after adding an item to my realtime database. Despite following the documentation's proposed solution, I am encountering issues with its implementation. Following the use of the push().set() meth ...

What is the best way to redirect nodejs requests to a separate nodejs application?

Hello! I am currently working on a project to create an API gateway using Node.js and Express. The goal is to showcase a small-scale microservices architecture by routing requests to different microservices. For instance, if I have microservices A, B, and ...