Full-Hybrid Full-Hybrid - 5 months ago 18
Javascript Question

Unable to get Angular Factory Data into Controller

Trying to get data from a Factory and pass it into a controller to then be used in an ng-repeat. Not sure why, but the controller never runs the function established in the factory.

Controller

angular.module('myApp').controller('AppController',['$scope','ItemsFactory',
function($scope,ItemsFactory){
ItemsFactory.getItems(function(err, data){
$scope.items = data;
console.log('controller items', $scope.items);
});
}]);


Factory

angular.module('myApp').factory('ItemsFactory', function($http){
var getItems = function(){
$http({
method: 'GET',
url: 'js/data/data.min.json'
}).then(function success(response, data){
var results = response.data;
console.log('factory results', results);
}, function error(response){
console.log('error getting items');
});
};
return{
getItems: getItems
};
});


Followed a few other examples posted but nothing seems to work either



Results are returned by the factory, just unable to pass that through to the controller

Edit

Sincerely thank you everyone for your answers as they were all extremely useful, worked and shed a lot of light on promises and callbacks.

Decided to use @Fernando Fabreti answer as it was as close to what I was looking for as possible.

Factory

angular.module('myApp').factory('ItemsFactory', function($http){
var getItems = function(callback){
$http({
method: 'GET',
url: 'js/data/data.min.json'
}).then(function success(response, data){
var results = response.data;
if(callback) callback(null, results);
}, function error(response){
console.log('error getting items');
});
};
return{
getItems: getItems
};
});


Controller

angular.module('myApp').controller('AppController',['$scope','ItemsFactory',
function($scope, ItemsFactory){

ItemsFactory.getItems(function(err, data){
$scope.items = data;
console.log('controller items', $scope.items);
});
}]);

Answer

You need to define a callback param and "call" the callback once you get the results:

angular.module('myApp').factory('ItemsFactory', function($http){
    var getItems = function(cback){
      $http({
        method: 'GET',
        url: 'js/data/data.min.json'
      }).then(function success(response, data){
        var results = response.data;
        console.log('factory results', results);
        if (cback) cback(null, results); 
      }, function error(response){
        console.log('error getting items');
        if (cback) cback(response, null);
      });
    };
    return{
      getItems: getItems
    };
});