angularjs嵌套控制器不接收注入的服务

时间:2014-05-18 21:31:51

标签: angularjs

我显然不明白我认为必须在这里发挥作用的范围问题。尽管已经在angularjs中阅读了相当多的范围,并且在很多情况下看到它的工作正常。

但在这里我有2个嵌套控制器:

MainController [can inject RepositoryService]
 --> ChallengeController [cannot successfully inject RepositoryService]
    --> SingleChallengeController [cannot successfully inject RepositoryService]
 --> PlayerController [can inject RepositoryService]

MainController通过app.js中的$ routeProvider设置进行实例化:

myApp.config(function ($routeProvider) {
  $routeProvider
    .when('/', {
      templateUrl: 'views/main.html',
      controller: 'MainController'
    })
    .otherwise({
      redirectTo: '/'
    });
});

以下是应用声明:

...
  <body ng-app="myApp">
    <div id="m" class="section app-viewport" ng-view=""  ng-keydown="keyPress($event);"></div>
...

同时其他3个控制器在main.html中内联指定,如下所示:

main.html中:

    <div id="viewport" viewport ng-hide="isPhone && isLandscape" class="section main">
      <div class="container-fluid">
        <div main-panel-row-maximize-height class="row main-panel-row">
          <div class="main-panel">
            <div class="row">
              <div id="challenge-options-results" challenge-panel-init class="challenge-option-results display-visible" >
                <section ng-controller="ChallengeController" class="challenge-container">
                  <div class="container-fluid">
                    <div class="row">
                  <div ng-controller="SingleChallengeController"/>
                </div>
              </div>
            </section>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="display-hidden" id="controls-and-badges">
    <div id="readout" ng-controller='PlayerController'  class="balance">
    <span class="readout-label balance">data</span><hr class="balance-separator">
      <span class="amount" ng-bind="currData">$NaN</span>
    </div>
...

我试图使用'构造函数'将服务('RepositoryService')注入这些控制器,如下所示:

var challengeControllers = angular.module('challengeControllers', []);

challengeControllers.controller('ChallengeController', ['$scope',  function($scope,  eventBusService, RepositoryService) {
...

这种注入方式适用于MainController和PlayerController,但不适用于其他两种方法。

以下是我要注入的服务的构造函数:

var serviceModule = angular.module('RepositoryService', []);

serviceModule.factory("RepositoryService", ['$rootScope', function ($rootScope, $http) {

是否有任何明显的我遗漏的东西抑制了我认为与依赖注入相关的逻辑行为?

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您应该像这样编写控制器定义:

challengeControllers.controller('ChallengeController', ['$scope', 'eventBusService', 'RepositoryService', function($scope,  eventBusService, RepositoryService) {

您似乎忘了在此处的数组参数中添加eventBusServiceRepositoryService

顺便说一下,如果您不需要在生产中对此代码进行模糊处理,那么请不要使用明确命名的注射剂并写下这样的代码:

challengeControllers.controller('ChallengeController', function($scope,  eventBusService, RepositoryService) {