javascript - 如何在 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");
解决方案
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");
}])
有关详细信息,请参阅
推荐阅读
- javascript - 这两个函数签名如何传递给 then() 等效?
- ios - PageController 和图像 iOS 的 Swift ScrollView 布局问题
- c - 为什么我不能在 vs 代码中编译 c?
- node.js - Postman 套接字挂断无法连接到 Mongodb
- haskell - 如何声明我的属性属于记录中的某个类型类?
- c++ - 获取可调整大小的选择区域的 QTransform
- vim - Vim 中具有多个字符的本地领导者
- serialization - 自定义结构的多个 serde::Serialize 实现
- django - 如何在 django rest 框架中使用 prefetch_related 和 select_related
- html - 嵌套网格中的子级忽略父级填充