Noorus Khan
Noorus Khan

Reputation: 1476

AngularJS : Getting Error on adding $scope in factory-service

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;
        }]);

I am getting this error

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

If from studentService.js, $scope is being removed, i.e

app.factory('saveStudentService',['$http',function ($http) { 

this code is working properly, and not getting any error message in console.

Following is the studentController.js file from where this studentService is being called.

StudentController.js

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

}]);

but if same thing i.e $scope is being added in the updateStudentService then this code is working as expected.

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

}]);

Could someone please clarify, what is happening here. Though able to use same thing in one place, but not able to use same process at someother place.

Upvotes: 3

Views: 249

Answers (1)

user2009750
user2009750

Reputation: 3187

You cannot inject scope into services. You can inject it to controllers.

Upvotes: 5

Related Questions