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

1

5

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';
    });
Magulac answered 15/1, 2014 at 8:4 Comment(3)
Have you tried doing return path instead of doing return null in redirectTo function.Diabetic
@Diabetic .... argh, yes, that works ... I didn't try it because logic told me I would end up in an infinite loop. But the angular team seems a little smarter and they've handled it. Thanks for the helpMagulac
Adding it as answer, so that the question can be marked answered.Diabetic
D
7

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

Diabetic answered 15/1, 2014 at 9:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.