未知提供者:{0} angularjs调用服务

时间:2014-01-20 20:17:09

标签: angularjs service

如果我尝试在子模块内调用子模块的服务,我会收到错误“Unknown provider:{0}”

这里是mainModule脚本

var mainApp = angular.module("mainApp", ["categoriesApp","ui.router"]);

//a service in the mainmodule which i can call with no problems in the submodule
mainApp.factory("getDataSvc", ["$http", "$q", "path", function ($http, $q, path) {
  return{
    ...
    some $http
    ....
}]);

现在是子模块

var categoriesApp = angular.module("categoriesApp", []);

//i can inject and use getDataSvc with no problems from the mainmodule
categoriesApp.controller("listCtrl", ["$scope", "getDataSvc", function ($scope, getDataSvc){
  getDataSvc.categories().then(function(data){
    ...
  })
}])

//my service in the submodule
categoriesApp.factory("sharedDataSvc", ["$scope", function ($scope){
  return{
    getValue: function(){
      return "oioioioi";
    }
  }
}])

//in this line i get the error, if i try to inject the sharedDataSvc  
//if i dont inject it, i get no errors, but cant use the service ;)
categoriesApp.controller("addBtnCrtl", ["$scope", "sharedDataSvc", function ($scope, sharedDataSvc){
  console.log(sharedDataSvc.getValue());
}])
希望有人能告诉我我做错了什么;)

1 个答案:

答案 0 :(得分:1)

问题在于sharedDataSvc factory

您无法将$scope注入工厂,因为$scope不是注册提供商 $ scope仅注入控制器(在本地对象中)。

categoriesApp.factory("sharedDataSvc", [ function (){
  return{
    getValue: function(){
      return "oioioioi";
    }
  }
}])
  • 每个控制器可以多次实例化(每个实例$ scope是不同的范围)
  • 每个服务只实例化一次然后缓存(相同的实例注入到处)