mercredi 27 avril 2016

Dynamically building AngularJS routes at runtime based on JSON config

I have a JSON config that I'd like to build my angular routes based off of. In essence, I'd like the angular app to fetch the json, build the routes, then bootstrap the application. I've come up with a working solution, but it doesn't seem to follow the standard angular paradigm and I'd like to figure out what patterns to use to adapt it properly. Perhaps as a service/factory or separate module?

JSON:

{
    "routes" : [
        {
            "route_name"              : "home",
            "route"                   : "/",
            "visible_in_menu"         : true,
            "menu_title"              : "Home",
            "menu_font_awesome_icon"  : "fa-home",
            "controller"              : "HomepageController",
            "template"                : "app/templates/home.html",
            "child_routes"            : null
        },
        {
            "route_name"              : "discover",
            "route"                   : "/discover",
            "visible_in_menu"         : true,
            "menu_title"              : "Discover",
            "menu_font_awesome_icon"  : "fa-search",
            "controller"              : "DashboardAppController",
            "template"                : "app/templates/dashboard.html",
            "child_routes"            : null
        }
    ],

}

Fully functioning Code:

var app = angular.module('dashboardApp',['ngRoute', 'ngAnimate', 'ui.bootstrap']);


// Grab dashboard config, load angular app
fetchData().then(bootstrapApplication);


/**
 * Grabs the dashboard configuration prior to the angular application
 * being loaded.
 */
function fetchData() {
    var initInjector = angular.injector(["ng"]);
    var $http = initInjector.get("$http");

    return $http.get("app/routes_menu_config.json").then(function(response) {
        app.constant("routes_menu_config", response.data);
    }, function(errorResponse) {
        // Handle error case
    });
}


/**
 * Enables the angular application
 */
function bootstrapApplication() {
    buildRoutes();
    angular.bootstrap(document, ["dashboardApp"]);
}


/**
 * Method for building the application's routes at run time based on the routes_menu_config.json 
 */
function buildRoutes(){

    // Grab the JSON extracted from the config file
    var routesAndMenuConfig = angular.injector(['dashboardApp']).get('routes_menu_config');

    var routes = routesAndMenuConfig["routes"]; 

    // Configure angular routes based on JSON
    app.config(['$routeProvider', '$locationProvider',
        function($routeProvider, $locationProvider) {

            for(var i=0; i < routes.length; i++){

                var currentRoute = routes[i];

                // If the current node actually has a route, add it
                if(currentRoute.route){
                    $routeProvider.
                        when(currentRoute.route, {
                            templateUrl: currentRoute.template,
                            controller: currentRoute.controller
                    });
               }

               // If the current node actually has child routes, add them
               if(currentRoute.child_routes){
                    for(var j=0; j < currentRoute.child_routes.length; j++){
                        var currentChildRoute = currentRoute.child_routes[j];

                        $routeProvider.
                            when(currentChildRoute.route, {
                                templateUrl: currentChildRoute.template,
                                controller: currentChildRoute.controller
                      });
                    }
               }

            }

    }]);

}

Aucun commentaire:

Enregistrer un commentaire