Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS catch-all route?

I'm working on a file editing application in AngularJS. My urls look like this:

#/fileName.md

or

#/folder/fileName.md

or

#/folder/nested-folder/another-folder/itgoesonforever/filename.MD

I don't want to have to do a route for every single depth and it could be ~15 routes deep. Are there any ways to have conditional routes? Crudely:

/:fileorfolder?/:fileorfolder?/:fileorfolder?/:fileorfolder?
like image 794
wesbos Avatar asked Jul 10 '13 17:07

wesbos


2 Answers

I think the best you can do with Angular is *, which is new as of v1.1.5 of $routeProvider:

path can contain named groups starting with a star (*name). All characters are eagerly stored in $routeParams under the given name when the route matches.
For example, routes like /color/:color/largecode/*largecode/edit will match /color/brown/largecode/code/with/slashes/edit and extract:
- color: brown
- largecode: code/with/slashes

You'd have to parse the largecode param yourself though.

like image 51
Mark Rajcok Avatar answered Oct 26 '22 17:10

Mark Rajcok


I think I got it! The trick is to set the template to a simple , then modify the scope to include the dynamic path to your template.

So now I can place a file at /foo/bar/baz.html and see the template rendered by going to server.com/foo/bar/baz.

// Routes
app.config( function($routeProvider) {
    $routeProvider

    // Home
    .when( '/', {
        templateUrl: 'home.html',
        controller: 'HomeController'
    })

    // Catch All
    .when( '/:templatePath*', {
        template: '<ng-include src="templatePath"></ng-include>',
        controller: 'CatchAllCtrl'
    })

});

// Catch All Controller
app.controller("CatchAllCtrl", function($scope, $routeParams) {
    $scope.templatePath = $routeParams.templatePath + '.html';
});
like image 31
df-sean Avatar answered Oct 26 '22 18:10

df-sean