首页 > 解决方案 > 如何在 AngularJS 中向 app.module() 动态添加控制器?

问题描述

我在 AngularJS 中工作,我制作了一个函数,它接受一些参数并将它们传递给 angularjs 的方法。我试图弄清楚这是否可以使用 console.log 工作,但它不会在控制台上打印任何内容。它只是行不通。

是什么阻止我传递要附加到角度模块变量的参数(动态创建的控制器)?

这是JS代码的片段:

app.controller('mainController', ["$scope", function ($scope) {.....

   //.... a lot of code...

  function createControllers(ControllerName, tab) {      
      app.controller(ControllerName, function (
          $scope,
          $rootScope,
          $http,

          ) {    
            console.log(ControllerName);
            init($scope, $rootScope, tab);
            obtenerParametros($http);
            watch($scope);
            guardarParametros($scope, $rootScope, tab);
            EditarParametros($scope, $rootScope, "Correcciones");
            limpiarParametro($scope, tab);
            eliminarParametro($scope, $rootScope, tab);
           SeleccionarParametro($scope, $rootScope);    
           mostrarFormatoPorDefecto($scope);
            if (ControllerName === 'GeneralController') {
                console.log('yes, Im the first');
            }   
        });
   }

  createControllers("GeneralController", "General");
  createControllers("ParametrosController", "CEMS");    
  createControllers("CorreccionesController", "Correcciones");
  createControllers("CilindrosController", "Cilindros");
  createControllers("EquiposController", "Equipos");
  createControllers("DPController", "DP");
  createControllers("MPController", "MP");

标签: javascriptangularjs

解决方案


AngularJS 框架分两个阶段运行:config阶段和run阶段。控制器只能在config阶段添加。一旦run阶段开始,应用程序就无法更改其配置,包括添加额外的控制器、指令、过滤器、服务等。

config阶段中将控制器添加到应用程序模块:

app.config(["$controllerProvider", function ($controllerProvider) {

  //.... a lot of code...

  function createConstructor(ControllerName, tab) {      
     function controllerConstructor($scope, $rootScope, $http) {    
        console.log(ControllerName);
        init($scope, $rootScope, tab);
        obtenerParametros($http);
        watch($scope);
        //...
        mostrarFormatoPorDefecto($scope);
        if (ControllerName === 'GeneralController') {
            console.log('yes, Im the first');
        }   
     }
     controllerConstructor.$inject = ["$scope", "$rootScope", "$http"];
     return controllerConstructor;
   }

   function register(controllerName, tab) {
       var constructorFn = createConstructor(controllerName, tab);
       $controllerProvider.register(controllerName, constructorFn);
   } 

   register("GeneralController", "General");
   register("ParametrosController", "CEMS");    
   register("CorreccionesController", "Correcciones");
   register("CilindrosController", "Cilindros");
   register("EquiposController", "Equipos");
   register("DPController", "DP");
   register("MPController", "MP");
}])

有关详细信息,请参阅


推荐阅读