3

Is it possible to pass multiple values into a '.when' call during routing? For example,

$routeProvider
    .when('/page1' || '/page2', 
    {

    });

Or would I have to call them individually like:

$routeProvider
    .when('/page1', 
    {

    })
    .when('/page2', 
    {

    });

I'm able to call them individually, but I want only a specific set of top-level pages. I'm wanting to know if I can bundle to save ~15 lines of extra code, or if I will have to call them individually.

1 Answer 1

1

You can use named groups:

$routeProvider.
    when('/page:id'), {
        templateUrl: 'page-template.html',
        controller: 'PageCtrl'
    }).
    when('/404'), {
        templateUrl: '404.html',
        controller: 'NotFoundCtrl'
    }).
    otherwise({
        redirectTo: '/404'
    });

http://docs.angularjs.org/api/ngRoute.$routeProvider

PageCtrl

app.controller('PageCtrl', function($routeParams, $location) {
    switch ($routeParams.id) {
    case 1:
    case 2:
    case 3:
    case 4:
        // code for your base pages
        break;
    default:
        $location.path('/404'); // not base pages, 404
        break;
    }
    // other code
});

In this way, if the url isn't one of /page1, /page2, /page3 or /page4, the view will be redirected to 404 page.

Sign up to request clarification or add additional context in comments.

4 Comments

Well, I have four base pages that I want to use a certain template, but I want to redirect the other top-level pages to a 404 or home page or something. So, if :page is 'page1', 'page2', 'page3', or 'page4', then go to those pages, but if :page isn't one of those, go to the 404. I can add the provisions individually, but I'm wondering if there's a way to group.
Hmm... that is a solution, but I'm really just curious as to if I can do it within the physical .when() call.
@Chad I don't think the bundled route module can do this at this moment.
@Chad Check this out github.com/gregorypratt/AngularDynamicRouting, he is trying to achieve even more dynamical routing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.