title: angularjs $http.get to get json not working in the service layer
body: <p>I am developing an angularjs app as a part of my angularjs learning. I have controllers and from there I am calling service layers.</p>
  <pre><code>leagueManager.service(&quot;teamsService&quot;, function($http){
      var teams = {};
          $http.get('data/teams.json').then(function(data) {
          teams = data;
      });
      this.getTeams = function(){
          return teams;
      };
  </code></pre>
  <p>});</p>
  <p>I noticed that because of the asynchronous nature of $http.get.then stuff, the data is not retrieved immediately and hence I would not get the &quot;teams&quot; when I would call getTeams() from the controller (teamsController), I would get nothing.</p>
  <p>Any idea how do I resolve this?</p>
  <p><strong>Second Attempt:</strong>
  After reading about deferred and promises on angular as suggested by the post below, I tried following but it still has no effect. My variable <strong>teams</strong> is not being populates as I want and they are populated afterwards and that is not helping in my UI:</p>
  <p><em>My controller</em> <strong>teamsController.js</strong></p>
  <pre><code>leagueManager.controller('teamsController', function($scope, $location, teamsService, $routeParams){
  //init function to initialize data when controller is called everytime.
  var init = function(){
          $scope.teams = [];
          var promise = teamsService.getTeams();
          promise.then(
          function(data){
              console.log(&quot;teams after promise:=&quot;+data);
              $scope.teams = data;
          }
          ,function(reason)
          {
                  alert('Failed: ' + reason);
          }
          );
          console.log(&quot;teams in the scope:=&quot;+$scope.teams);
  };
  
  init();
  });
  </code></pre>
  <p>And here is my <em>ServiceLayer</em> <strong>teamsService.js</strong></p>
  <pre><code>leagueManager.service(&quot;teamsService&quot;, function($http, $q){
  this.getTeams = function(){
    var deferred = $q.defer();
       var url = 'data/teams.json';
       $http.get(url).success(function(data, status) {
           // Some extra manipulation on data if you want...
           deferred.resolve(data);
       }).error(function(data, status) {
           deferred.reject(data);
       });
       return deferred.promise;
  }
  });
  </code></pre>
  <p>Can you or someone help me what I am doing wrong?
  This is what is printed in the browser console upon execution:</p>
  <blockquote>
  <p>teams in the scope:= teamsController.js:27</p>
  <p>teams after promise:=[object Object],[object Object],[object Object],[object Object],[object Object]</p>
  </blockquote>
  <p>This simply shows that I do get the json object but not at the time I want. For some reason this deffered/promise thing had no impact.</p>
  <p><strong>PLEASE HELP THIS NEW ANGULAR ENTHUSIAST</strong></p>