在路径配置中使用AngularAMD加载动态控制器

时间:2014-11-14 15:37:12

标签: angularjs requirejs angular-amd

我有下一个路线配置:

    .config(["$routeProvider", function ($routeProvider) {
        $routeProvider
            .when('/something/:id', angularAMD.route({
                templateUrl  : function ($routeParams) {
                    return "views/something/" + $routeParams.id + ".html";
                },
                controllerUrl: function ($routeParams) {
                    return "controllers/something/" + $routeParams.id + "/main";
                }
            }))

似乎angularAMD不支持controllerUrl作为函数,因此我无法定义控制器的动态。

问题是如何为不同的网址加载不同的控制器,我错过了什么或者有另一种解决方法?

1 个答案:

答案 0 :(得分:2)

你可以尝试类似下面的东西。它取自本网站(http://www.codeproject.com/Articles/808213/Developing-a-Large-Scale-Application-with-a-Single

 $routeProvider.when("/something/:id", angularAMD.route({
                templateUrl: function (rp) { return 'views/' + rp.section + '/' + rp.tree + '.html'; },

                resolve: {

                    load: ['$q', '$rootScope', '$location', function ($q, $rootScope, $location) {

                        var path = $location.path();
                        var parsePath = path.split("/");
                        var parentPath = parsePath[1];
                        var controllerName = parsePath[2];

                        var loadController = "Views/" + parentPath + "/" + controllerName + "Controller";

                        var deferred = $q.defer();
                        require([loadController], function () {
                            $rootScope.$apply(function () {
                                deferred.resolve();
                            });
                        });
                        return deferred.promise;
                    }]
                }

            }))