根据路由组动态加载控制器

时间:2014-01-03 17:39:01

标签: angularjs angularjs-controller angular-routing

是否可以根据路由组动态加载控制器,js文件和模板? Psuedo代码不起作用:

$routeProvider.when('/:plugin', function(plugin) {
  templateUrl: 'plugins/' + plugin + '/index.html',
  controller: plugin + 'Ctrl',
  resolve: { /* Load the JS file, from 'plugins/' + plugin + '/controller.js' */ }
});

我看过很多像这样的问题,但没有一个问题根据路由组加载js文件/控制器。

4 个答案:

答案 0 :(得分:15)

我设法通过@calebboyd,http://ify.io/lazy-loading-in-angularjs/http://weblogs.asp.net/dwahlin/archive/2013/05/22/dynamically-loading-controllers-and-views-with-angularjs-and-requirejs.aspx

启发解决它

使用http://dustindiaz.com/scriptjs

<强> app.js

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

然后我注册“按组加载控制器”路径。

$routeProvider.when('/:plugin', {

  templateUrl: function(rd) {
    return 'plugin/' + rd.plugin + '/index.html';
  },

  resolve: {
    load: function($q, $route, $rootScope) {

      var deferred = $q.defer();

      var dependencies = [
        'plugin/' + $route.current.params.plugin + '/controller.js'
      ];

      $script(dependencies, function () {
        $rootScope.$apply(function() {
          deferred.resolve();
        });
      });

      return deferred.promise;
    }
  }
});

<强> controller.js

app.register.controller('MyPluginCtrl', function ($scope) {
  ...
});

<强>的index.html

<div ng-controller="MyPluginCtrl">
  ...
</div>

答案 1 :(得分:3)

您可以使用RequireJS执行此操作。类似的东西:

$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;
    }}
});

您还需要动态注册控制器。通过在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
        };
});

您的控制器文件可能如下所示:

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

这只是一般的想法。我使用与here

描述的类似的实现

我也使用ui-router。我不确定行为是否与ngRoute相同。

答案 2 :(得分:2)

以下是您可以为此代码执行的解决方案

$routeProvider.when('/:plugin', function(plugin) {
  templateUrl: 'plugins/' + plugin + '/index.html',
  controller: fun,
  loadFrom:"assets/controller/myJsController"// this is our custom parameter we are passing to controller to identify the remote controller file.
});

我们将为所有控制器创建一个父函数,并按照路由配置中的定义调​​用此函数中的所有控制器(在路由配置的loadFrom键中)。

 function fun($scope, $http, $location, $timeout, $route) {
        $timeout(function () {
        var path = $route.current.loadForm;
        $http.get("${pageContext.servletContext.contextPath}/resource/controller/" + path + ".js")
                .then(function (rsp) {
                eval(rsp.data);
                });
        });
        };

assets / controller / myJsController.js 文件中代码将为

(function($scope){
//the whole code for controller will be here.
   $scope.message="working."


 })($scope)

只有您必须记住,在父函数中,您必须使用所有依赖项。

答案 3 :(得分:0)

以最少的代码激活此方法的最简单方法

require.js配置文件。

&#13;
&#13;
require.config({
    urlArgs: 'v=1.0',
    baseUrl: '/'
});
&#13;
&#13;
&#13;

&#13;
&#13;
app.config(['$controllerProvider', '$compileProvider', '$filterProvider', '$provide','$routeProvider',function($controllerProvider, $compileProvider, $filterProvider, $provide,$routeProvider) {
  app.register = {
    controller: $controllerProvider.register,
    directive: $compileProvider.directive,
    filter: $filterProvider.register,
    factory: $provide.factory,
    service: $provide.service
  };
  // Resolver to load controller, service, directive
  var resolveController = function(dependencies) {
      return {
        load: ['$q', '$rootScope', function ($q, $rootScope) {
          var defer = $q.defer();
          require(dependencies, function () {
              defer.resolve();
              $rootScope.$apply();
          });
          return defer.promise;
        }]
      }
  };
  $routeProvider
    .when("/home", {
        templateUrl : "templates/home.html",
        controller: 'HomeCtrl',
        resolve: resolveController(['controller/HomeCtrl'])
    })
    .when("/ContactUs", {
        templateUrl : "templates/ContactUs.html",
        controller: 'ContactUsCtrl',
        resolve: resolveController(['controller/ContactUsCtrl'])
    })
    .when("/About", {
        templateUrl : "templates/About.html",
        controller: 'AboutCtrl',
        resolve: resolveController(['controller/AboutCtrl'])
    });
  $routeProvider.otherwise('/home');
}]);
&#13;
&#13;
&#13;

你的控制器应该是这样的。

&#13;
&#13;
define(['app'],function(app){
    app.register.controller('HomeCtrl',['$scope',function($scope){
      // Controller code goes here
    }]);
});
&#13;
&#13;
&#13;