'/' is not letting the state to pass to &#

2019-08-01 21:29发布

问题:

I have a abstract root state called 'site' with empty url i.e. '' , which has two child state 'profile' and 'home' where the url for home is '/' and the url for profile is '/{username:[a-zA-Z0-9]{3,20}}' inorder to test I tried many times to go to the profile state but it always reaches the home state.

But when i change the home state url with say '/home' then i'm able to go to the profile state. After searching the web i couldn't find this issue. Is it a bug? or i'm doing something wrong?

Here is the code for $stateProvider

     $stateProvider.
        state('site', {
            url: '',
            abstract: true,
            views: {
                '': {
                    templateUrl: 'views/site.html' //this is the base template
                },
                'navbar@site': {
                    templateUrl:'views/navbar.html'
                }
            },
            data:{
                access: access.public
            }
        }).
        state('site.home', {
            url: '/',
            templateProvider :['$rootScope','$http','$state',function($rootScope,$http,$state){
                //console.log($state);
                var template = 'views/main_new.html';
                if($rootScope.User.isLoggedIn()){
                    template = 'views/new_room_me.html'
                }
                return $http.get(template).then(function (resp) {
                    return resp.data;
                });
            }]
        }).
        state('site.profile',{
            url:'/{username:[a-z0-9A-Z]{3,20},strict:true}',
            templateUrl:'views/new_room_friend.html'
        });


       $urlRouterProvider.otherwise('/ankit');

回答1:

There is a working example, where I mostly switched the order of state declaration:

.state('site.profile',{
        url:'/{username:[a-z0-9A-Z]{3,20}}',
        ...
    })
.state('site.home', {
        url: '/',
        ...
    })

The reason is that ui-router url engine does iterate states in order they were declared, and tries to find a url match. this way, we will get the working definition.

But I would suggest:

use some keyword to distinguish url, e.g. url:'/profile/{username:[a-z0-9A-Z]{3,20}}',

Not only this will help the engine to find the proper state by url, but even from perspective of the user/reader of the url - this seems to me more explicit, self-descriptive.

Anyhow, switching state def should solve the issue here...