AngularJS:在工厂服务中添加$ scope时出错

Kha*_*han 3 javascript angularjs

studentService.js

   app.factory('saveStudentService',['$http','$scope',function ($http,$scope) { 
            var studentData = {};
            studentData.save = function(jsondata){
                var action = "student";
                var method = "POST";
                $http({
                    url: action,
                    method: method,
                    headers: {'Content-Type': 'application/json'},
                    data: jsondata
                }).success(function(data, status, headers, config) {
                    toastr.success(status +' : Data has been submitted successfully ');
                }).error(function(data, status, headers, config) {
                    toastr.error(status + ' : Data has not been submitted successfully ');
                });
            };
            return studentData;
        }]);
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误

angular.js:13642Error: [$injector:unpr] http://errors.angularjs.org/1.5.6/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20saveStudentService
    at Error (native)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:6:412
Run Code Online (Sandbox Code Playgroud)

如果来自studentService.js,则删除$ scope,即

app.factory('saveStudentService',['$http',function ($http) { 
Run Code Online (Sandbox Code Playgroud)

此代码工作正常,并没有在控制台中收到任何错误消息.

以下是studentController.js文件,该文件来自此studentService.

StudentController.js

app.controller('saveStudentCtrl',['$scope', 'saveStudentService', function($scope,saveStudentService) { 
    $scope.submit_create_student = function() {
        var jsondata = $scope.student;
        saveStudentService.save(jsondata);
    }

}]);
Run Code Online (Sandbox Code Playgroud)

但是如果同样的事情,即在updateStudentService中添加$ scope,则此代码按预期工作.

app.controller('updateStudentCtrl',['$scope','retriveStudentService', 'updateStudentService', function($scope,retriveStudentService, updateStudentService) {    
    $scope.getStudentDataFromServer = function() {      
        retriveStudentService.get();
    };
    $scope.submit_update_student = function(e) {
        updateStudentService.update();
    }

}]);
Run Code Online (Sandbox Code Playgroud)

有人可以澄清一下,这里发生了什么.虽然能在同一个地方使用相同的东西,但是不能在其他地方使用相同的处理.

ɢʜʘ*_*ɔʘɴ 5

您无法将范围注入服务.您可以将其注入控制器.

  • 是的,您不会将$ scope注入服务.有时您会将$ rootScope注入服务,例如,它需要广播系统范围的事件.服务设计为全局对象,而范围设计用于保存上下文数据. (2认同)