【问题标题】:there is a common error Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- methodService有一个常见错误 Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- methodService
【发布时间】:2015-12-08 19:21:20
【问题描述】:

我的代码如下:

var module = ons.bootstrap('my-app', ['onsen','ngSanitize','ngCookies','ngStorage']);
  module.factory('methodService', [ '$scope', '$timeout', '$http', 
                                    '$localStorage', 'alertService', 
               function($scope, $timeout, $http, $localStorage, alertService){
}]);


  module.factory('alertService', function () {
    var data = {
      title: 'Alert',
      message: ''
    }
    return {
      getTitle: function () {
        return data.title;
      },
      setTitle: function (title) {
        data.title = title;
      },
      getMessage: function () {
        return data.message; 
      },
      setMessage: function (message) {
        data.message = message;
      },
      alert : function(){
        ons.notification.alert({
          message: data.message,
          title: data.title
        });
      }
    };
  });

还有一个错误Error: [$injector:unpr] Unknown provider: $scopeProvider

有人知道原因和解决方法吗?

【问题讨论】:

  • 可以这样写吗? module.factory('methodService', function($scope, $timeout, $http, $localStorage, alertService) { });
  • 也有这个错误
  • 可能是因为alertService,你能把那个代码也贴出来吗?
  • 工厂没有$scope...
  • 如何在工厂使用?

标签: angularjs onsen-ui


【解决方案1】:

你对两件事有误解:

  • 如 cmets 中所说,$scope 是一个特殊变量,只能注入到控制器中
  • 注入到控制器中的作用域对象对于每个控制器都不同。它不是对象的同一个实例。 Angular 是这样构建的:你有一个 $rootScope。每个其他 $scope 都继承自该 $rootScope 或另一个 $scope。这是一个树层次结构。由于继承,您可以检索存储在父 $scope 中的数据。

我的建议:不要存储 $scope,不要向 $rootScope 发送垃圾邮件。只需将您需要的内容存储在控制器的 $scope 中,然后像这样正确调用您的工厂层:

$scope.myObjectToCreate = {};//object that wll be field in a form
$scope.createObject = function(){
    myService.create($scope.myObjectToCreate);
}
//or 
$scope.createObject = function(object){
     myService.create(object);
}
// but NEVER DO THIS
$scope.createObject = myService.create;

最后一点是关于将要更改的函数的范围,在函数myService.create 中每次使用this 都会使其崩溃。因为这将引用$scope 而不是myService

【讨论】:

    猜你喜欢
    • 2016-11-12
    • 2015-08-12
    • 2016-05-26
    • 2016-05-09
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    相关资源
    最近更新 更多