javascript – AngularJs在app.config中的回调中配置路由

我开发了一个我需要的应用程序,路由必须加载动态模板,例如:

当我点击/ myclient /#!/ details时,我需要从“myclient”目录加载模板.

我有一个json API,可以为每个客户端响应此配置.

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

因此,我在尝试将angular.config设置为此API响应的回调时遇到问题.我还尝试在回调后设置路由.

我认为这个解决方案很合适.我究竟做错了什么?

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);

});

最佳答案 Drica!

使用@dfsq发送的这个实现,它将起作用,但这一部分

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

如果你使用ui-route,则没有必要.
否则,在/ route中出现此问题,可以使用localStorage保存json信息并重新加载页面.在我的测试中,它有效.

点赞