1

我有一个 EmailAccountsController,我需要将“Hosting”和“EmailAccount”服务注入其中。这是我的代码:

hostingsModule.controller('EmailAccountsCtrl', ['$scope', 'Hosting', 'EmailAccount', function ($scope, Hosting, EmailAccount) {
    var hostingId = 1
    $scope.hosting = Hosting.find(hostingId);
    $scope.emailAccounts = EmailAccount.all(hostingId)
}]);

错误信息是TypeError: Cannot call method 'all' of undefined

当我只将一项服务注入同一个控制器时,一切正常。有没有办法将多个服务注入一个控制器?

编辑:我试图将所有相关代码放入一个文件中。它看起来像这样:

hostingsModule.factory('Hosting', ['$http', function($http) {
    var Hosting = function(data) {
        angular.extend(this, data);
    };

    Hosting.all = function() {      
        return $http.get('<%= api_url %>/hostings.json').then(function(response) {
            return response.data;
        });
    };

    Hosting.find = function(id) {
        return $http.get('<%= api_url %>/hostings/' + id + '.json').then(function(response) {
            return response.data;
        });
    }

    return Hosting; 
}]);

hostingsModule.factory('EmailAccount', ['$http', function($http) {
    var EmailAccount = function(data) {
        angular.extend(this, data);
    };

    EmailAccount.all = function(hostingId) {        
        return $http.get('<%= api_url %>/hostings/' + hostingId + '/email-accounts.json').then(function(response) {
            return response.data;
        });
    };

    EmailAccount.find = function(id) {
        return $http.get('<%= api_url %>/hostings/' + id + '.json').then(function(response) {
            return response.data;
        });
    };
}]);

hostingsModule.controller('EmailAccountsCtrl', ['$scope', 'Hosting', 'EmailAccount',     function($scope, Hosting, EmailAccount) {
    var hostingId = 1;

    $scope.hosting = Hosting.find(hostingId);
    $scope.emailAccounts = EmailAccount.all(hostingId)

    console.log($scope.hosting);
    console.log($scope.emailAccounts);
}]);
4

1 回答 1

2

范围问题。您需要返回EmailAccount,因为它是在闭包内初始化的。你需要return EmailAccount;像你所做的那样添加Hosting

或者试试这个代码:

hostingsModule.factory('EmailAccount', ['$http', function ($http) {
    var service = {
        all: function (hostingId) {
            return $http.get('<%= api_url %>/hostings/' + hostingId + '/email-accounts.json').then(function (response) {
                return response.data;
            });
        },

        find: function (id) {
            return $http.get('<%= api_url %>/hostings/' + id + '.json').then(function (response) {
                return response.data;
            });
        }
    }
    return service;
}]);
于 2013-07-30T15:36:40.400 回答