$htttp.get doesn't return proper data when it's in services.js

Hi friends,

I’ve got tab-news.html:

<ion-view view-title="Wiadomości">
  <ion-content class="padding">
    <div class="list card" ng-repeat="article in news">
      <div class="item item-divider"><b>{{article.header}}</b></div>
      <div class="item item-body">{{article.text}}</div>
    </div>
  </ion-content>
</ion-view>

and controlers.js:

.controller('NewsCtrl', function($scope, $http) {
	$http.get('http://www.patryk.t15.org/zsti/news.php').success(function(response){
		$scope.news=response;
	})
})

All works fine, I get list with data in my app, items are showing

But when $http.get function is in services.js like here:

angular.module('starter.services', [])
.factory('News', function($http) {
	var news=[];
	
	$http.get('http://www.patryk.t15.org/zsti/news.php').success(function(response){
		news=response
	})
	
	return {
    all: function() {
      return news;
    }
  };
})

and controlers.js looks like:

angular.module('starter.controllers', [])
.controller('NewsCtrl', function($scope, News) {
	$scope.news=News.all()
})

It doesn’t work :frowning: List in my app is empty. There is no error in Firebug.
Probably I made some a stupid mistake but I don’t know where.

Thanks in advance for help :slight_smile:

That’s because the http call is async. Read about $q which is a service that helps you in these scenarios (promises).

Change your factory as follows:

.factory('News', function($http) { 
  return {
    all: function() {
      return $http.get('http://www.patryk.t15.org/zsti/news.php');
    }
  };
})

And your controller:

$scope.news = [];

News.all().then(function(news) {
  $scope.news = news;
});

Thank you very much. From now I know what are promises and where i made mistakes :smile: