Search code examples
javascriptangularjspromiseangular-services

AngluarJS controller getting returned factory but not displaying in template


My controller is calling the service factory, I see the factory doing API calls successfully and returning the results to the controller, but the template assigned to the controller is not rendering the results.

Factory:

.factory("clubService", function($http,$q) {
  var clubs= [] ;
  function clubsAll() {
    clubs = [] ;
    setVars() ; // function to set baseUrl/headers, etc   
    var dataObj = [{"type":1,"userID":userData.user_ID}]
    var req = {
      method: 'POST',
      url: baseUrl ,
      headers: headers,
      data: JSON.stringify(dataObj)
    }
    return $http(req)
    .then(function(response){
      clubs = response.data ;
      return clubs ;
    }).catch(function(err) {
      errMgmt("services/apiCall",700,err.code+", "+err.msg) ;
    });
  }

  return {
    all: function() {
      return clubsAll() ;
      //return clubs ;
    }
}) ;

Controller:

.controller('ClubCtrl', function($scope,$state,clubService) {

  $scope.clubs = clubService.all() ;
  console.log($scope.clubs) ;   // 'clubs' is getting populated in console.
})

And in my HTML

   <div ng-if="clubs.length == 0">
      <img ng-src="img/loader.gif">
   </div>
   <div ng-if="clubs.length > 0">
      <div ng-repeat="club in clubs">
         {{club.Name}}
      </div>
   </div>

But nothing in my HTML is getting rendered, anything referencing clubs is not showing, ng-if is still commented out, no ng-repeat display.


Solution

  • In the clubService, clubsAll() method, you are actually returning a promise when you state this line

    return $http(req)
        .then(function(response){
          clubs = response.data ;
          return clubs ;
        }).catch(function(err) {
          errMgmt("services/apiCall",700,err.code+", "+err.msg) ;
        });
    

    That promise can either be resolved(success) or rejected(error) and if you want to get the clubs data from that promise you need to chain on your controller logic on the promise success callback (.then)

    .controller('ClubCtrl', function($scope,$state,clubService) {
    
        clubService.all().then(function(response){
            $scope.clubs = response;
        });
    })