Angularjs工厂:传递$ scope,$ route,$ http时出错?
当$scope, $route, $http
存在时,为什么我的工厂在下面继续抛出错误?
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; }); } }; });
我不能把$scope, $route, $http
传递给工厂吗?
我测试了这个基本的,它给了我同样的错误,
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; }; });
我该怎么办?
错误,
Error: [$injector:unpr] http://errors.angularjs.org/1.2.6/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20factoryContacts ...
我不能把$ scope,$ route,$ http传递给工厂吗?
为什么不是范围
您不能将$ scope注入service / factory,它的singleton并具有本地范围 。 但是你可以使用$rootScope
传递$route
和$http
使用注入和写入如下:
app.factory("factoryContacts",['$route','$http', function($route,$http){ return { getContacts: function(){ return $http({ method: 'GET', url:'php/listContacts.php' }).then(function(response) { //.... }); } }; }]);