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

AngularJs configure route in callback inside app.config

本文关键字:回调 配置 路由 AngularJs app config      更新时间:2023-09-26

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

当我点击/myclient/#时/详细信息我需要从"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中,您可以使用localStorage来保存您的json信息并重新加载页面。在我的测试中,它起了作用。

当您将数组传递到runRote函数时,不必字符串路由数组。在它中,您对传递的数据使用forEach方法,这是一个数组方法,而不是字符串。正确的代码应该是:

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

此外,其他路线的配置应为

redirectTo: "templates/404.html"