Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 331
Noorus Khan Avatar asked Jun 24 '26 17:06

Noorus Khan


1 Answers

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

like image 50
KKK Avatar answered Jun 26 '26 05:06

KKK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!