控制器无法获取服务数据

时间:2013-11-14 11:02:55

标签: angularjs

我有ServiceController。控制器调用getItems()上的函数ServiceService会返回array个数据。

然而,奇怪的是,控制器似乎没有收到这个。

控制器:

ItemModule.controller('ItemController', ['$scope', 'ItemService',
    function ($scope, ItemService) {

        $scope.items = [];

        $scope.getItems = function() {
            $scope.items = ItemService.getItems();
        }

        $scope.getItems();

    }
]);

服务:

ItemModule.service('ItemService', ['$rootScope', '$http', 
    function($rootScope, $http) {

        this.getItems = function() {
            $http.get($rootScope.root + '/products').success(function(data) {
                // This prints it out fine to the console
                console.log(data);
                return data;
            });
        }

    }
]);

我做错了什么?

1 个答案:

答案 0 :(得分:0)

快速且修复就是这样:

ItemModule.service('ItemService', ['$rootScope', '$http', 
function($rootScope, $http) {

    return {
        getItems : function(scope) { 
            $http.get($rootScope.root + '/products').success(function(data) {
                scope.items = data;
            });
        }
    }

}
]);

然后在您的控制器中调用:

 ItemService.getItems($scope);

但是如果您的控制器是路线的一部分(可能是),那么使用resolve(看here)会更好。