I have some nested routes defined dinamically:
var res = [
{i:1,title:"title 1"},
{i:2,title:"title 2"},
{i:3,title:"title 3"},
{i:4,title:"title 4"}
];
app.config(function($stateProvider, $urlRouterProvider, $authProvider,$httpProvider) {
// other routes [...]
angular.forEach(res, function(d) {
$stateProvider.state('nested.q' + d.i, {
url: '/' + d.i,
template: '{{d.i}} - {{d.title}}'
});
});
});
var res
should be retrieved in ajax from the server, I'm not sure how to accomplish that in this step of the angular workflow (earlier that any service or controller loads).
EDIT based on @Radim Köhler answer I tried this code, what's wrong with this? the routes simply aren't registered:
var $stateProviderRef; // is this global var used like you thought??
app.config(function($stateProvider, $urlRouterProvider,$httpProvider,$locationProvider) {
$stateProvider
.state('about', {
url: "/about",
templateUrl: "/partials/about.html"
})
$urlRouterProvider.deferIntercept();
$locationProvider.html5Mode({enabled: false});
$stateProviderRef = $stateProvider;
$urlRouterProvider.otherwise('/');
});
app.run([ '$rootScope','$http', '$urlRouter',
function ($rootScope, $http, $urlRouter)
{
$http
.get("/api/remoteStates")
.success(function(data)
{
angular.forEach(data, function (value, key)
{
console.log(value)
$stateProviderRef.state(value.name, {
url: value.url,
template: value.template
});
});
$urlRouter.sync();
$urlRouter.listen();
});
}]);
/api/remoteState response:
[
{
"name": "state1",
"url": "state1",
"template": "<h1>state1</h1>"
},
{
"name": "state2",
"url": "state2",
"template": "<h1>state2</h1>"
}
]