AngularJS,$ routeProvider和resolve:Hello World示例不起作用

时间:2014-11-26 21:42:28

标签: angularjs

我正在尝试使用$routeProviderresolve的Hello World示例整合到控制器中。 This is the plunk;我得到的错误是Unknown provider: greetingService但工厂是在控制器和配置之前声明的。这段代码出了什么问题?

的index.html:

<body ng-controller="mainCtrl">

   <a href='#option1'>click me to show Hello World</a>

   <br/><br/>

   {{message}}

   <br/><br/>

   *****

   <div ng-view></div> 

   *****


</body>

template.html:

<div ng-controller="templateCtrl">
   {{hello}}
</div

app.js:

angular.module('app', ['ngRoute']);


angular.module('app')
.factory("greetingService", function($q, $timeout){
   return {
       getGreeting: function(){
           var deferred = $q.defer();
           $timeout(function(){
               deferred.resolve("Hello");
           },1000);
           return deferred.promise;
       }
   };
});


angular.module('app')
.controller('mainCtrl', function($scope) {

     $scope.message = "Message in the main controller";
});

angular.module('app')
.controller('templateCtrl', function($scope,greeting) {

    $scope.hello = greeting + " World";

});

angular.module('app')
.config(function($routeProvider,greetingService) {

    $routeProvider.
      when('/option1', {

        templateUrl: 'template.html',
        controller: 'templateCtrl',
        resolve: {
            greeting: function(greetingService){
                return greetingService.getGreeting();
            }
        }

      });
  });

1 个答案:

答案 0 :(得分:2)

这是因为您在主greetingService中注入了app.config。删除该行,它将起作用:

http://plnkr.co/edit/GRqZQrEvKa6dntx39qOu?p=preview

您只能将提供者注入配置块(即$ locationProvider,$ routeProvider),而不是实例。您可以将实例注入应用的.run块。