使用AngularJS和RequireJS按需加载控制器

时间:2014-10-08 23:34:56

标签: angularjs angularjs-scope angular-ui-router

我使用Angular UI-router并在路由更改时尝试下载/加载控制器。我使用了resolve和category,data.data以字符串形式返回js文件内容。我不确定让控制器可用于角度。请帮忙

我的module.js包含以下路由代码

state("privacy", {
        url: "/privacy",
        controllerProvider: function ($stateParams) {
            return "PrivacyController";
        },
        resolve: {
            category: ['$http', '$stateParams', function ($http, $stateParams) {
                return $http.get("js/privacy.js").then(function (data) {
                    return data.data;
                });
            } ]
        },
        templateUrl: localPath + "templates/privacy.html"
    })

以下控制器存在于" js / privacy.js"

  

socialinviter.controller(" PrivacyController",function($ scope){   $ scope.me =" Hellow world&#34 ;;   });

我也试过了需要js,但我收到了错误" http://errors.angularjs.org/1.2.16/ng/areq?p0=PrivacyController&p1=not%20aNaNunction%2C%20got%20undefined"

resolve: {
            deps: function ($q, $rootScope) {
                var deferred = $q.defer(),
                    dependencies = ["js/privacy"];
                    require(dependencies, function () {
                        $rootScope.$apply(function () {
                            deferred.resolve();
                        });
                        deferred.resolve()
                    })
                return deferred.promise;
            }
        }

1 个答案:

答案 0 :(得分:2)

我已经解决了这个问题,我认为这个解决方案对其他人有帮助

步骤1:在您的配置上,包含参数$ controllerProvider

mytestapp.config(function ($stateProvider, $controllerProvider) 

步骤2:告知angular将下载的控制器注册为控制器,在config

中添加以下内容
mytestapp.config(function ($stateProvider, $controllerProvider) {
mytestapp._controller = mytestapp.controller
mytestapp.controller = function (name, constructor){
    $controllerProvider.register(name, constructor);
    return (this);
}
......

步骤3:添加如下解决方法

state("privacy", {
        url: "/privacy",
        controller: "PrivacyController",
        resolve: {
            deps : function ($q, $rootScope) {
                var deferred = $q.defer();
                require(["js/privacy"], function (tt) {
                    $rootScope.$apply(function () {
                        deferred.resolve();
                    });
                    deferred.resolve()
                });
                return deferred.promise;
            }
        },
        templateUrl: "templates/privacy.html"
    })