我试图将我的控制器传递到另一个控制器并且我不断收到错误:[$ injector:unpr]未知提供者:MchControllerProvider< - MchController
如何将一个控制器正确注入另一个控制器?这是我的代码:
此部分是GroupMaintenanceBrowsePlansCtrl->
(function () {
'use strict';
var controllerId = 'GroupMaintenanceBrowsePlansCtrl';
angular.module('myApp').controller(controllerId, ['$scope', 'RenewalGroupDataService', 'logger', 'mchService', 'MchController' , Controller]);
function Controller($scope, datacontext, logger,mchService, MchController) {
logger = logger.forSource(controllerId);
...
此部分是MchController - >
'use strict';
myApp.controller('MchController', function ($scope, $routeParams, mchService, CustomerDataService, EntityInfoService, RatesDataService, RenewalGroupDataService) {
console.log('reached MchController');
//Rout parameters as passed via App.js
$scope.routeParams = {
type: $routeParams.Type,
id: $routeParams.Id
};
//Properties associated with data
$scope.visible = {
experience: true,
persistency: true,
}
// define view model and expose it to the scope
var vm = {
title: 'Loading MCH Name... ',
CustomerNumber: 'Loading MCH Number...'
};
$scope.vm = vm; //local scope to MchController
vm.type = $routeParams.Type;
vm.id = $routeParams.Id;
vm.togglePlans = togglePlans;
vm.toggleRates = toggleRates;
vm.getRateInformation = getRateInformation;
vm.getMch6 = getMch6;
vm.Mch2Information = [];
vm.searchParameters = mchService.searchParameters;
function togglePlans()
{
vm.expandedPlans = !vm.expandedPlans;
}
//Puts multiple sets of Mch2 data into array to iterate through
vm.Mch2Information = new Array();
vm.getEntityInformation = function () {
getEntityInformation('MCH', mchService.searchParameters);
}
//Initialize GET command for Customer Information
//getEntityInformation($routeParams.Type, $routeParams.Id);
function getEntityInformation(type, id)
{
switch (type)
{
case "MCH": getCustomerInformation(id);
//getMch6();
getMch2Information(id);
....
答案 0 :(得分:1)
您不能通过依赖注入将一个控制器注入另一个控制器,但您可以嵌套控制器并利用嵌套控制器之间的原型继承:
<body ng-controller="MainCtrl">
<div ng-controller="ChildCtrl">
<p>Hello {{name}}!</p>
<button ng-click="parentAction()">parent action</button>
<button ng-click="overriddenAction()">overriden action</button>
</div>
</body>
js code:
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.parentAction = function () {
alert('greetings from parent controller')
};
$scope.overriddenAction = function () {
alert('greetings from parent controller');
};
});
app.controller('ChildCtrl', function ($scope) {
$scope.overriddenAction = function () {
alert('greetings from child controller');
};
})
这样您就可以访问父控制器上定义的函数和对象。或者您可以事件覆盖这些对象或函数。
http://plnkr.co/edit/Kmi4wm3aYrOf1shpmM5D?p=preview
如果您想了解有关angularjs中原型继承的更多信息,我建议您阅读此问题:What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
答案 1 :(得分:0)
您无法将控制器注入另一个控制器。如果两个控制器之间存在共享逻辑,则将其放入服务中并将其注入控制器。
理想情况下,您的控制器应该尽可能地薄,并且业务逻辑的大多数(如果可能的话)都应该驻留在服务中。