Dynamic Routing in AngularJS – Can I retrieve data from server before setting up $routeProvider?-Collection of common programming errors

Update: @dnc253 — angular-detour is now ready enough that I think you could use it to get routes loaded from json. It’s not yet well-documented and doesn’t have tests, so it’s certainly not complete in that sense, but the merging of json into a live instance of the router has been working for a while.

If you’re still looking for a way to use server defined routes, you can read instructions on running the samples and then check out the third sample’s mergeJson call in app.js. Feedback would be great — I’m getting started on real documentation/tests now, so there’s no need to tell me that the documentation sucks and there aren’t any tests — I’m on that one. 🙂 Hopefully the samples are enough to squeak by if this functionality is still on your list of needs

Older part of the answer: If you just want a static set of routes that are defined by the server with JSON, you could use something like JQuery to fetch your routing data before you configure your app.

Pseudocode:

$.ajax({
  url: "http://example.com/routes"
  }
}).done(function ( data ) {
    angular
        .module('myApp',[])
        .config(function($routeProvider) {
          //read routing instructions from data and call "when" on $routeProvider to define the routes
         });

});

This should work with ui-router as well. But it only enables you to fetch an initial set of routes, so while it gives you the possibility of data-driven definitions, they are only driven by the data that was available when the app was loaded by the client.

As eazel7 points out, you can access providers at run time if you create your own service that binds to the provider at config time. However, to do what you want to do you need to go out of process to do an $http call, and with the current routers (the stock Angular core and ui-router) you won’t get your answer in time to populate the router before a deep link fails when someone visits your site. Additionally both of those routers use functions to populate the routing “table” and thus do not lend themselves to having the routing updated after it has been initially configured.

I’m working on something that addresses these issues, such that if a requested route is unknown to the router, it will attempt to fetch it from the server before invoking the fallback route or failing. Also will support checking for modifications to known routes. Essentially lazy routing with an AJAX/JSON interface to the server. It’s based on ui-router, and is living at https://github.com/afterglowtech/angular-detour . It currently implements the editability of routes but I haven’t done the laziness/server communication pieces. That’s next on my list. Keep an eye on it, it should end up doing what you’re looking for.