使用AngularUI路由器动态负载控制器负载、路由器、控制器、动态

2023-09-13 03:40:27 作者:烟酒嗓

我用 UI路由器在一个应用程序,将有几十个模板。每个模板将有一个控制器。

I'm using ui-router in an app that will have dozens of templates. Each template will have a controller.

这是我一直在读,这样的事情(设置路由)什么应该工作:

From what I've been reading, something like this (to setup a route) ought to work:

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('start', {
      url: '/start',
      templateUrl: 'partials/start.html',
      controller: 'StartCtrl'
    })
});

这是假设StartCtrl是pviously定义$ P $。该应用程序将最终有几十个控制器,并且不希望下载所有这些一次的开销。我如何可以加载一个控制器仅在请求模板?

That's assuming StartCtrl was previously defined. The app will eventually have dozens of controllers, and don't want the overhead of downloading all of them at once. How can I load a controller only when the template is requested?

推荐答案

我用这个RequireJS。和一个供应商,说lazyProvider:

I use RequireJS for this. And an in a provider, say lazyProvider:

在你懒的提供商...

In your lazy provider...

this.resolve = function(controller){
    return { myCtrl: ['$q',function ($q){
            var defer = $q.defer();
            require(['/app/controllers/'+controller,'myApp'],function(ctrl,myApp){
                myApp.register.controller(controller,ctrl);
                defer.resolve();

            }
            return defer.promise;
        }]
    };
};

在你的UI路由器解析:属性来完成:

In your ui-router resolve: property do:

resolve: lazyProvider.resolve('myCtrl');

您需要在您的应用程序供应商公开登记,以便您可以将它们稍后注册,如:

You'll need to expose provider registers on your app so you can register them later, like:

myApp.config(function($urlRouterProvider, $stateProvider,
          $controllerProvider, $compileProvider, $filterProvider,$provide){
    //If your myApp isn't already a module...
    define('myApp',[],function(){return myApp});
    myApp.register = {
        controller: $controllerProvider.register,
        directive: $compileProvider.directive,
        filter: $filterProvider.register,
        factory: $provide.factory,
        service: $provide.service,
        constant: $provide.constant
    }

和你的控制器:

define(['/dependencies'],function(deps){
    function MyCtrl($scope){...}
    return MyCtrl;
}

这实质上是丹Wahlin共用这里

This is essentially what Dan Wahlin has shared here

 
精彩推荐