Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular ui-router go to URL

How to use $state.go() if I have just the URL ?

Or can I get a state based on URL? (and than use $state.go(state))

I'm asking because I had to intercept the $urlRouterProvider.otherwise() to wait for an other plugin loads some external modules.. and now I need to continue and call the URL that call otherwise()

like image 223
Falci Avatar asked Jun 11 '15 21:06

Falci


3 Answers

In place of $state.go(), you can use $location service as well.

i.e.

$location.path(url)

Please take care of not using # in URL. You can also use window.location.href

like image 151
Nikhil Aggarwal Avatar answered Nov 07 '22 04:11

Nikhil Aggarwal


I had a similar problem, and $location wasn't helping, so I wrote a function to get the state from the url.

NB: I am using nested states based on ui-router.stateHelper, so I traverse my nested states object, testing for url matches. It would be slightly different when using dot notation to define nested states - and even easier if you don't use nested states at all!

function goPath (path) {
    var target;

    var arr = path.match(/\/\w+/g);
    var i = 0;

    var testState = function (state, i) {
        if (state.url === arr[i]) {
            target = state;
            if (state.children && state.children.length && arr.length > i+1) {
                i++;
                state.children.forEach( function (childState) {
                    testState(childState, i);
                });
            } 
        }
    };

    myStatesObj.forEach( function (state) {
        testState(state, i);
    });

    $state.go(target.name);
};
like image 2
StevieP Avatar answered Nov 07 '22 02:11

StevieP


I was on a similar situation, what I did is changed the location to a different path and reset it to the current after a timeout like this

var path = $location.path();
$location.path("/");

$timeout(function(){
    $location.path(path).replace(); //use .replace() so the empty path won't go to the history
},0);
like image 1
Louie Almeda Avatar answered Nov 07 '22 02:11

Louie Almeda