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;
}]);
我收到这个错误
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
如果来自 studentService.js,$scope 被删除,即
app.factory('saveStudentService',['$http',function ($http) {
此代码运行正常,并且在控制台中没有收到任何错误消息。
以下是调用此 studentService 的 studentController.js 文件。
StudentController.js
app.controller('saveStudentCtrl',['$scope', 'saveStudentService', function($scope,saveStudentService) {
$scope.submit_create_student = function() {
var jsondata = $scope.student;
saveStudentService.save(jsondata);
}
}]);
但如果在 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();
}
}]);
有人可以澄清一下,这里发生了什么。虽然可以在一个地方使用相同的东西,但不能在其他地方使用相同的过程。
最佳答案
您不能将作用域注入(inject)服务。您可以将其注入(inject) Controller 。
关于javascript - Angular : Getting Error on adding $scope in factory-service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39193921/