Angularjs factory: errors on passing $scope,$route,$http?

喜夏-厌秋 提交于 2019-12-11 08:48:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!