nofear87
nofear87

Reputation: 869

$http data from service to controller

iam searching for a way to transfer the requested data from my service to the controller. a simple return data dont work....i wondering why?

test.factory('DataService', function($http, $log) {

    return {

        getEmployees: function( ) {

            $http({method: 'GET', url: 'php/data.php'})
                .success ( function ( data, status, header, config ){

                    //return data

                })
                .error ( function ( data, status, header, config ){

                    $log.log ( status );

                })

        },

        getTest: function( ) {

            return "test123";

        }

    };

});


test.controller('employees', function ( $scope, DataService ) {

    $scope.test = DataService.getEmployees();

});

Thank you. Robert

Upvotes: 0

Views: 109

Answers (1)

Satpal
Satpal

Reputation: 133403

You can use $q and promise. $http is an asynchronous call

factory

test.factory('DataService', function($http, $log, $q) {
    return {
        getEmployees: function( ) {
            var d = $q.defer();
            $http({method: 'GET', url: 'php/data.php'})
                .success(function(data, status, header, config){
                    d.resolve(data);
                }.error(function(error){
                    d.reject(error);
                });
            return d.promise;
        },
        getTest: function( ) {
            return "test123";
        }
   };
});

Controller

DataService.getEmployees().then(function(data){
    $scope.test = data;
});

Upvotes: 2

Related Questions