Adding query string to UI router route

2019-08-24 19:12发布

问题:

I have a ui router route that is defined as follows

        $stateProvider
        .state('search', {
            url: '/search',
            abstract: true,
            parent: 'loggedIn',
            views: {

                wrapper: {
                    controller: 'MyCtrl',
                    controllerAs: 'myCtrl',
                    templateUrl: '/scripts/views/search/views/search.wrapper.html'
                }
            }
        })
        .state('search.subs', {
            url: '',
            resolve: {
                isLoggedIn: isLoggedIn
            },
            views: {
                body: {
                    controller: 'SearchBodyCtrl',
                    controllerAs: 'searchBodyCtrl',
                    templateUrl: '/scripts/views/search/views/search.body.html'
                }
            }
        });

Anyways the issue is that I cannot generate a query parameters so that the url looks like /search?hello=world I tried using $state.transitionTo('search.subs', {hello: 'world'}) but that didn't work. I figured any params I passed that did not match would just be put in the query string but that is not the case.

回答1:

This should do what you want to do:

    .state('search.subs', {
        url: '?hello', // This appends to the parent url
          ....

Afterwards you can just use $state.go('search.subs', { hello : 'world' }) to transition to the search.subs state.

https://github.com/angular-ui/ui-router/wiki/URL-Routing#query-parameters