Load controller dynamically based on route group

前端 未结 4 918
夕颜
夕颜 2020-12-08 17:29

Is it possible to load a controller, it\'s js file, and a template dynamically based on a route group? Psuedo code which doesn\'t work:

$routeProvider.when(\         


        
4条回答
  •  被撕碎了的回忆
    2020-12-08 18:05

    You can use RequireJS to do this. Something like:

    $routeProvider.when('/:plugin',{
        templateUrl: 'plugins/' + plugin + '/index.html',
        controller: plugin + 'Ctrl',
        resolve: {myCtrl: function($q){
            var deferred = $q.defer();
            require('myCtrlFile',function(){
                deferred.resolve();
            });
            return deferred.promise;
        }}
    });
    

    You will also need to register the controller dynamically. By exposing your providers in the app config.

    app.config(function($controllerProvider,$compileProvider,$filterProvider,$provide){
        app.register =
            {
                controller: $controllerProvider.register,
                directive: $compileProvider.directive,
                filter: $filterProvider.register,
                factory: $provide.factory,
                service: $provide.service
            };
    });
    

    You controller file might then look like:

    define(['app'],function(app){
        app.register.controller('myCtrl',MyCtrlFunction);
    });
    

    This is just the general idea. I use a similar implementation to the one described here

    I also use ui-router. I'm not certain if behavior is the same with ngRoute.

提交回复
热议问题