0

私はServiceとを持っていControllerます。コントローラは で関数を呼び出しgetItems()ますService。はデータのをService返します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;
            });
        }

    }
]);

私は何を間違っていますか?

4

1 に答える 1

0

A quick and dirty fix would be like that:

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

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

}
]);

and then in your controller just call:

 ItemService.getItems($scope);

But if your controller is a part of route (and probably is) it would be much nicer to use resolve (look here).

于 2013-11-14T14:59:44.030 に答える