1

I'm learning AngularJS and assuming this is possible, so what is the best way to create routes dynamically based on the results of an API call?

I have a controller which returns an array of folders:

controllers.controller('FoldersCtrl', function($scope, $http) { 
  $http.jsonp('https://api....=JSON_CALLBACK').then(function (shaggy){
    $scope.list=shaggy.data;
});

I've seen several examples of $routeProvider which look something like this:

app.config(function ($routeProvider) {
  $routeProvider
  .when('/somePath', {controller:"SomePathCtrl", templateUrl: "partials/somePath.html" })
  .otherwise({redirectTo: "/homePath"})
});

But I've yet to encounter an example where the '/somePath' is derived from the result of an API call. I'd like to do something like this:

app.config(function ($routeProvider) {
  $routeProvider
  .when({{shaggy.data.folder}}, {controller:"FolderCtrl", templateUrl: "partials/folder.html" })
  .otherwise({redirectTo: "/homePath"})
});

Then ideally, both FolderCtrl and partials/folder.html would be populated with code generic enough to display the objects in each folder so some how the would have to be aware of the {{shaggy.data.folder}} that I passed to the route. Any thoughts?

Thanks in advance.

Chris
  • 115
  • 9

1 Answers1

0

$routeProvider can only be configured in the config method of a module, which will run before anything else in that module (like services or controllers).

One way you could achieve this is to use a catch-all route:

$routeProvider.when('/:somePath*', ...)

and use $routeParams to emulate the behaviour.

A loose (theoretical) example:

.controller('RouteController', function($routeParams) {
  this.viewPath = $routeParams.showPath + '.html';  // or some way to map routes to views.
});

<div ng-controller="RouteController as routeCtrl">
  <div ng-include="{{routeCtrl.viewPath}}"></div>
</div>

We have a (not open-source) app where we create a JS variable with the routing information during the initial server page render, something like:

<script>var ROUTES = <% routes %>;</script>

where routes is a JSON dump of a map from the server (skipping an API call from JS). Then, we simply set up the $routeProvider:

.config(function($routeProvider) {
  angular.forEach(JSON.parse(ROUTES), function(view, route) {
    $routeProvider.when(route, {templateUrl: view});
  });
})
arunjitsingh
  • 2,644
  • 2
  • 22
  • 16