简体   繁体   中英

AngularJs configure route in callback inside app.config

I developing an application that I need that the routes must load dynamic templates, for an example:

When I hit /myclient/#!/details I need to load templates from "myclient" directory.

I have an json API that responds this configurations for each client.

[{
    "path": "/",
    "templateUrl": "template/loja1/index.html",
    "controller": "homeController"
}, {
    "path": "/detail",
    "templateUrl": "template/loja1/detail.html",
    "controller": "homeController"
}];

So, I'm having issues trying to setup the angular.config as callback for this API response. I also tried to setup the routes after callback.

I think that this solution would fit. What am I doing wrong?

var app = angular.module("myApp", ['ngRoute']);

app.config(function($routeProvider, $locationProvider, $provide) {

    $locationProvider.hashPrefix('!');

    var API = $provide.factory('API', function($http) {
        return {
            getStore: function() {
                return $http.get("http://localhost:8080/resources/route");
            }
        };
    });

    var runRote = function(routes) {

        routes.forEach(function(route) {
            $routeProvider.when(route.path, {
                templateUrl: route.templateUrl,
                controller: route.controller
            });
        });
        $routeProvider.otherwise({
            redirectTo: "templates/404.html"
        });
    };

    var getRoutes = function(runRote) {
        API.$get().getStore().success(function(data, status) {
            runRote(JSON.stringify(data));
        }).error(function(data, status) {
            runRote();
        });
    };

    getRoutes(runRote);

});

You don't have to stringify routes array when you pass it into runRote function. In it you are using forEach method on passed data which is an array method, not string. Correct code should be:

var getRoutes = function(runRote) {
    API.$get().getStore().success(function(data, status) {
        runRote(data);
    }).error(function(data, status) {
        runRote();
    });
};

Also configuration for otherwise route should be

redirectTo: "templates/404.html"

Drica!

Using this implementation that @dfsq send, it will work, but this part

app.controller('homeController', function($route) {
    window.route = $route;
});

is not necessary if you use ui-route. Otherwise, this problem in the / route, you can use localStorage to save your json information and reload the page. In my tests, it worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM