Configuring UI Router states based on configuration

angular-ui-router, angularjs, state

Solution

I would say, that there are in general two ways how to use SERVER data (JSON) to build up states.

Firstly, we can use `$http` to load the JSON:

AngularJS - UI-router - How to configure dynamic views

The point here is, that we will in `.config()` state store reference to `$stateProvider` and use it in `.run()` phase, once the JSON could be loaded via `$http`

// ref to provider, to be configured later
var $stateProviderRef;

// config phase
app.run(['$stateProvider',
  function ($stateProvider) 
  {
    $stateProviderRef = $stateProvider
  }

// run phase
app.run(['$q', '$rootScope', '$state', '$http',
  function ($q, $rootScope, $state, $http) 
  {
    $http.get("myJson.json")
    .success(function(data)
    {
      angular.forEach(data, function (value, key) 
      { 
          var state = {
            "url": value.url,
            ...
          };
          ...
          // here we still configure provider, but in RUN
          $stateProviderRef.state(value.name, state);
      });

But there are some disadvantages. The main is, that direct url navigation (copy - paste) won't be working. The URL will not be rosolved soon enough...

Secondly, my preferred way - create JSON as variable on a server, load it as a script.

So server will somehow generate response via /api/stateData like:

var stateData  = [{ stateName : "State1",
  ...
}];

And we will inject that into page as a resource

<script src="/api/stateData" ...

This could be directly used in `.config()` phase, and will solve issue with `URL` being configured soon enough.

Problem

Is there a way to configure a UI Router states based on Server Side JSON file. I wan't to avoid hard coding the States inside my `module.config(..)`. I firstly thought of having controller which has the state map data available which can just call `$stateProvider`. However, I believe, controllers cannot have providers injected into them. The other option I have thought was having a Javascript file outside of angular which puts the state configuration data in some global variable to be referenced from Module config function. But is there a better approach?

Original source

Related problems