Search code examples
javascriptruby-on-railsangularjsresturl-routing

AngularJS Restful Routing


I'm trying to structure my app using the Restful/Ruby convension /<resource>/[method]/[id]. How I've done it previously when using a server-side MVC framework like CodeIgniter was to dynamically route based on the URI:

ex.

www.foo.com/bar/baz/1

The app would then use method baz in controller/class bar and return views/bar/baz.php (populated with data from bar->baz)

I would like to do the same in Angular, but I'm not sure if it supports this (and if it does, I'm not sure exactly how to go about it). At the moment I'm using $routeProvider's when method to specify each case. $location.path() looks like it might have what I need, but I don't think I can use it in app.js (within config()).

What I'd like to do is something like this:

.config([
  '$routeProvider', function($routeProvider) {
    $routeProvider
    .when(//<resource> controller exists
      resource+'/'+method, {
        "templateURL": "views/" + resource + "/" + method + ".html",
        "controller":  resource
      }
    ).otherwise({ "redirectTo":"/error" });
  }
]);

And the router automatically calls the appropriate method.

EDIT Also, why does $routeProvider freak out when I specify when('/foo/bar', {…}) ?

EDIT 2 Per Lee's suggestion, I'm looking into doing something like this:

$routeProvider
  .when(
    '/:resource/:method/:id', {
      "templateUrl": function(routeParams){
        var path = 'views/'+routeParams.resource+'/';
        return ( typeof routeParams.method === 'undefined' ) ?
          path+'index.html' : path+routeParams.method+'.html';
      },
      "controller": RESOURCE
  })
  .otherwise({redirectTo: '/error'});

I noticed the following in $routeProvider's doc:

screenshot from Dash. full text below

templateUrl – {string=|function()=} – path or function that returns a path to an html template that should be used by ngView.

If templateUrl is a function, it will be called with the following parameters:

• {Array.<Object>} - route parameters extracted from the current $location.path() by applying the current route

Edit: The option to set templateUrl to a function is part of the unstable 1.1.2 build: #1963 (but it doesn't work as of 2013-02-07).

There is a dicussion about adding this functionality on AngularJS's Github: #1193 #1524, but I can't tell if it was actually implemented (in the docs from Dash quoted above, it looks like it has been, and the docs on the site haven't been updated yet).

EDIT 3 To clarify what I want to happen (per lee's request), in simplest terms, I would like to go to www.foo.com/index.html#/people

Angular should use controller people, automatically call its index method, and should serve up

./views/people/index.html
./views/people/map.html

Also, if I go to www.foo.com/index.html#/people/map

Angular should use the people controller again, but this time automcatically call its map method and serve up …map.html (because map was specified in the url)

./views/people/index.html
./views/people/map.html

Then, if I go to

www.foo.com/index.html#/widgets

Angular should serve up

./views/widgets/index.html
./views/widgets/details.html

The code for the router should be very generic—I shouldn't have to specify a .when() for every route.


Solution

  • This is now possible with ui-router 0.2.8:

    $stateProvider
        .state('base', {
            url: '/:resource/:collection/:id',
            controllerProvider: function( $stateParams )
            {   // assuming app.controller('FooCtrl',[…])
                return $stateParams.collection + 'Ctrl';
            },
            templateUrl: function( $stateParams )
            {
                return '/partials/' + $stateParams.collection + '.html';
            }
        });
    

    But in order to take advantage of $state.includes() on nav menus, this would probably be better:

    $stateProvider
        .state('base.RESOURCE_NAME1', {
            url: '/:collection/:id',
            controllerProvider: function( $stateParams )
            {   // assuming the convention FooCtrl
                return $stateParams.collection + 'Ctrl';
            },
            templateUrl: function( $stateParams )
            {
                return '/partials/' + $stateParams.collection + '.html';
            }
        }).state('base.RESOURCE_NAME2', {
            url: '/:collection/:id',
            controllerProvider: function( $stateParams )
            {   // assuming the convention FooCtrl
                return $stateParams.collection + 'Ctrl';
            },
            templateUrl: function( $stateParams )
            {
                return '/partials/' + $stateParams.collection + '.html';
            }
        });
    

    The above could be simplified with a loop to build the states from an array of resources ($stateProvider supports adding states basically whenever):

    var resources = [ 'r1', 'r2', '…' ];
    
    for ( var r = resources.length-1; r >=0; r-- )
    {
        var name = resources[r];
        $stateProvider.state('base.'+name, {
            …
        });
    }
    

    Caveat ui-router doesn't not really support optional state parameters (planned for v0.4)