Ahmed
Ahmed

Reputation: 1776

how to use factory in controller angularjs

I am trying to create factory and use it in the controller, the factory return data from get method and save it in the controller but its not working, and $scope.myData return undefind.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, myService) {
    $scope.myData = myService.getEvent();
});
app.factory('myService', function($http){
    var oGetData = {};
    oGetData.getEvent = function(){
        $http.get('http://citysdk.dmci.hva.nl/CitySDK/events/search?category=festival')
        .then(function(response) {
         return response.data.event;
        });
    };

    return oGetData ;
});

when i use factory code directly in the controller its work fine

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http.get('http://citysdk.dmci.hva.nl/CitySDK/events/search?category=festival')
        .then(function(response) {
            $scope.myData = response.data.event;
        });
});

can someone tell me what i did wrong in the first code please?

here is the codepen http://codepen.io/anon/pen/NRVZdE

Upvotes: 0

Views: 2712

Answers (1)

Pop-A-Stash
Pop-A-Stash

Reputation: 6652

Working Codepen: http://codepen.io/jdoyle/pen/KgLjgY

This is a commonly asked question. You are expecting this to return data, but it does not:

app.controller('myCtrl', function($scope, myService) {
    $scope.myData = myService.getEvent();
});

getEvent() returns a promise, not data. You need to treat the return object just like you would a call to $http:

app.controller('myCtrl', function($scope, myService) {
    myService.getEvent().then(function(response){
      $scope.myData = response.data.event;
    });
});

And in your factory just return the call to $http and nothing else:

oGetData.getEvent = function(){
    return $http.get('http://citysdk.dmci.hva.nl/CitySDK/events/search?category=festival');
};

If you want to modify the data before it comes back to the controller, you can create your own deferred and handle the response yourself, like this:

oGetData.getEvent = function(){
    var deferred = $q.defer();
    $http.get('http://citysdk.dmci.hva.nl/CitySDK/events/search?category=festival')
    .then(function(response) {
       deferred.resolve(response.data.event);
     });
    return deferred.promise;
};

Then you don't have to worry about getting the event from the response data:

app.controller('myCtrl', function($scope, myService) {
    myService.getEvent().then(function(event){
      $scope.myData = event;
    });
});

Upvotes: 1

Related Questions