1

Is it possible to configure AngularJS Routes with data from a JSON rest service?

Basically what I want to do is use this same data to generate a menu directive and the $routeProvider

module.config() will not accept injected services and module.run() does not seem like it mixes well with promise based data.

    var routeData = {
      routes    :
            [
                {
                    'routeUrl' : '/page1',
                    'title' : 'A home for Pizza',
                    'templateUrl' : '/Views/page1.html',
                    'controller' : 'AppCtrl'
                },
                {
                    'routeUrl' : '/page2',
                    'title' : 'Some YouTube video',
                    'templateUrl' : '/Views/page2.html',
                    'controller' : 'AppCtrl'
                },
                {
                    'routeUrl' : '/page3',
                    'title' : 'this is page 3',
                    'templateUrl' : '/Views/page3.html',
                    'controller' : 'AppCtrl'
                }
            ],
      defaultRoute : "/page1"
    };

overviewApp.config(['$routeProvider', function ($routeProvider) {
    var x, current;
    for (x in routeData.routes) {
        current = routeData.routes[x];

        $routeProvider.when(
            current.routeUrl,
            {
                templateUrl: current.templateUrl,
                controller: current.controller
            }
        );
    }

    $routeProvider.otherwise({
    redirectTo: routeData.defaultRoute
  });
}]);
RBZ
  • 2,034
  • 17
  • 34

1 Answers1

2

If you want to access services which are not typically available in the config phase, see angular service available at configuration phase. Alternatively, you have these other options:

  • Make an XHR request for your routeData before (manually) bootstrapping your Angular application. You can use:
    • the plain XMLHttpRequest object, or
    • a library/wrapper of your choice (jQuery, etc...), or
    • use a mini Angular app to access $http and make the request. This mini app is separate to your main Angular app. See Initialize AngularJS service with asynchronous data.
  • Have your server side retrieve and provide the routeData before Angular executes.

    <script src="//routeData.js"></script>

    <script src="//angular.js"></script>

Community
  • 1
  • 1
user2943490
  • 6,900
  • 2
  • 22
  • 38