问题
Why my factory below keep throwing an error when the $scope, $route, $http are present?
app.factory("factoryContacts",function($scope,$route,$http){
return {
getContacts: function(){
return $http({
method: 'GET',
url:'php/listContacts.php'
}).then(function(response) {
$scope.contacts = response.data;
});
}
};
});
can't I pass $scope, $route, $http into a factory?
I tested with this basic one and it gives me the same error,
app.provider('helloWorld', function($scope) { // note $scope is present
// In the provider function, you cannot inject any
// service or factory. This can only be done at the
// "$get" method.
this.name = 'Default';
this.$get = function() {
var name = this.name;
return {
sayHello: function() {
return "Hello, " + name + "! From Provider!!"
}
}
};
this.setName = function(name) {
this.name = name;
};
});
What should I do?
the error,
Error: [$injector:unpr] http://errors.angularjs.org/1.2.6/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20factoryContacts ... <ng-view class="ng-scope">
回答1:
can't I pass $scope, $route, $http into a factory?
why not $scope
You can't inject $scope into service/factory, its singleton and has local scope. But you can use $rootScope
To pass $route and $http use injection and write like:
app.factory("factoryContacts",['$route','$http', function($route,$http){
return {
getContacts: function(){
return $http({
method: 'GET',
url:'php/listContacts.php'
}).then(function(response) {
//....
});
}
};
}]);
来源:https://stackoverflow.com/questions/20829166/angularjs-factory-errors-on-passing-scope-route-http