Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs $routeProvider: using the redirectTo to redirect if a condition is met

I have these routes:

$routeProvider.when('/events/agenda', {...});
$routeProvider.when('/events/calendar', {...});
$routeProvider.when('/events/:id', {...});

The "/events/:id" route should only be matched if ":id" is a number... Currently, urls like "/events/whateverilike" are matched by that route.

So what I want to do is define my route as normal:

$routeProvider.when('/events/:id', { templateUrl: 'views/events/event-profile.html', controller: 'EventProfileCtrl',
    resolve: {
        event: function (EventLoader, $route) {
            return EventLoader({ id: $route.current.params.id });
        }
    });

but i want to make use of the redirectTo to validate the ":id" value. If its a number, continue to the view and controller, else redirect:

redirectTo: function(routeParams, path, search){
                        if (!+(routeParams.id)) // is :id a number?
                            return '/events/agenda';

                        return null;
                    }

but returning null doesn't negate the redirect.

I really don't want to put this logic on the controller as I believe the "url-matching" and validating should occur before going to the controller and view. Am I understanding this correctly, does it make sense what I'm trying to do?

Any help and suggestions would be much appreciated.

UPDATE: Having used the marked answer, I soon realized there was a problem with it if the url contained search params, ie: #/events/4450?join=true

Using "return path;" then removed the search params. This should rather be:

redirectTo: function(routeParams, path, search){
    if (!+(routeParams.id)) // is :id a number?
        return '/events/agenda';
}

End Result:

$routeProvider.when('/events/:id', { templateUrl: 'views/events/event-profile.html', controller: 'EventProfileCtrl',
    resolve: {
        event: function (EventLoader, $route) {
            return EventLoader({ id: $route.current.params.id });
        }
    },
    redirectTo: function(routeParams, path, search){
        if (!+(routeParams.id)) // is :id a number?
            return '/events/agenda';
    });
like image 815
Gavin van Gent Avatar asked Jan 15 '14 08:01

Gavin van Gent


1 Answers

Doing return path; instead on return null in redirectTo would fix the issue as the redirectTo should return a url it should navigate to.

like image 148
Chandermani Avatar answered Nov 22 '22 15:11

Chandermani