0

I have a need to create dynamic routing and I am unable to find anything that explains how I could do it..

If my route provider looks like this:

app.config(function($routeProvider) {
$routeProvider
    .when('/', {
        templateUrl:'/index.php',
    controller: 'mainCtrl'
    })
    .when('/search/:tags', {
        templateUrl:'/search/index.html',
        controller: 'searchCtrl'
    })
    .when('/path/one/', {
        templateUrl:'/test/two/partial.html',
        controller: 'testTwoCtrl'
    })
    .when('/path/one/:valueone', {
        templateUrl:'/mickey/mouse/partial.html',
        controller: 'MickeyMouseCtrl'
    })
    .otherwise({
        redirectTo: '/404.html'
    })
});

How can I generate it dynamically from a json object that holds required information,, something like this:

[
{
    "when": "/",
    "templateUrl": "/index.php",
    "controller": "mainCtrl"
},
{
    "when": "/search/:tags",
    "templateUrl": "/search/index.html",
    "controller": "searchCtrl"
},
{
    "when": "/path/one/",
    "templateUrl": "/test/two/partial.html",
    "controller": "testTwoCtrl"
},
{
    "when": "/path/one/:valueone",
    "templateUrl": "/mickey/mouse/partial.html",
    "controller": "MickeyMouseCtrl"
}
]

I also need to load this information in an XHR request. I suppose I am looking for something to this tune.. Is this viable, possible, doable?

app.config(function($routeProvider, $http) {

$http.get('routingdata.json').success(function(data) {
    for ( key in data ) {
        $routeProvider.when( data[key].when, {
            templateUrl:data[key].templateUrl,
            controller: data[key].controller
        })
    }
    $routeProvider.otherwise({
        redirectTo: '/'
    })    
   }
});
Cœur
  • 37,241
  • 25
  • 195
  • 267
GRowing
  • 4,629
  • 13
  • 52
  • 75
  • move the app.config part to inside the get function, although you might need to use plain js or manually get the $http dependency (or use jquery ajax) – JoseM Mar 13 '14 at 19:34
  • jQuery.. I am not allowed to use,,, but I will explore further the suggestion on moving the app.config to get function. Any samples I can look at? – GRowing Mar 13 '14 at 19:36
  • I just looked at your code again, have you actually tried your code, to me it seems like it should work – JoseM Mar 13 '14 at 19:43
  • I keep getting an error I am working on all along.. I will try an do a plunk of this.. The error comes about as soon as I inject $http into .config( function( $routeProvider, $http ) { – GRowing Mar 13 '14 at 19:49
  • I realized later that you can't inject $http there. [Plain js ajax](http://stackoverflow.com/a/3470944/238427) or [try this](http://stackoverflow.com/a/16476323/238427) – JoseM Mar 13 '14 at 20:04
  • Yeh,, just realized,, but I can inject $httpProvider,, thinking... ... – GRowing Mar 13 '14 at 20:07

0 Answers0