After adding a route programmatically, when any route is accessed, angular throws an error when back button is pressed

53 Views Asked by At

My problem is that after adding the below code, which adds dynamic routes to my web app, my back key throws an error that i cannot diagnose.

This is a simple provider method i came across a while back that adds this functionality:

myApp.provider('$dashboardState', function($stateProvider){
    this.$get = function($state){
        return {
            addState: function(title) {
                $stateProvider.state(title, {
                    url: '/' + title,
                    templateUrl: "templates/" + title + '.html'
                });
            }
        }
    }
})

I can then add a route to my ui-router in any of my controllers like so:

//variable $urlName is fetched previously and is just a string

$url_name = $urlName;
$dashboardState.addState($url_name);

When i do this, however, and i redirect to the route i have made dynamically by clicking:

<a href="#/" + $urlName + "\">

in my html, it works flawless except when i click the back key in my browser, the console throws this error:

[Error] Potentially unhandled rejection [1] 
registerState@http://epicbiz.shotsevolved.com/js/angular-ui-router.js:2361:53
state@http://epicbiz.shotsevolved.com/js/angular-ui-router.js:2871:18
addState@http://epicbiz.shotsevolved.com/js/app.js:22:37
http://epicbiz.shotsevolved.com/js/app.js:163:34
j@http://epicbiz.shotsevolved.com/js/built.min.js:13:3777
O@http://epicbiz.shotsevolved.com/js/built.min.js:13:3464
when@http://epicbiz.shotsevolved.com/js/built.min.js:13:6577
run@http://epicbiz.shotsevolved.com/js/built.min.js:13:5616
n@http://epicbiz.shotsevolved.com/js/built.min.js:11:25298
_drain@http://epicbiz.shotsevolved.com/js/built.min.js:11:25476
drain@http://epicbiz.shotsevolved.com/js/built.min.js:11:25250
r@http://epicbiz.shotsevolved.com/js/built.min.js:6:13467
    (anonymous function) (built.min.js:13:707)
    r (built.min.js:13:328)
    c (built.min.js:13:592)

I'm only very new to angular but any help would be greatly appreciated.

1

There are 1 best solutions below

1
On BEST ANSWER

When checking the source for angular-ui-router on line number 2361(that is where your error report said):

if (states.hasOwnProperty(name)) throw new Error("State '" + name + "' is already defined");

which means that u cannot register state with the same name twice.

However, when u back to the previous state, there could be chance that ur addState($url_name) is executed again. And this will cause the duplicate state name error.

Btw, i don't think it is a good idea to set states dynamically. If u insist on doing so, maybe check whether the state name is already there before adding it.