Search code examples
angularjsangular-servicesangular-controller

$http factory only working on first controller


I have a factory that is getting data and returning it to the controller. It works on the first controller, but returns nothing on the second. I was under the impression that I could pass this around to all the controllers. For a minute, I was thinking that maybe it could only be instantiated one time, so I created another factory with the same steps. Still same result. It returned an empty array in the second controller

//Factory

angular.module('myApp')
    .factory('classData', function($http){

      return {

        getClassData : function() {

          var studentData = [ ];

          $http({
            method: 'GET',
            url: 'theUrl'
          }).success(function(data){

            for(var i = 0; i < data.length; i++)
              studentData.push(data[i]);

          }).error(function(){
            alert("error", error);
          });

          return studentData;

        }
      };
    });


//Controller 1:

angular.module('myApp')
  .controller('studentListCtrl', function($scope, classData, statService) { //this controller is just view logic

    $scope.sortType     = 'attendanceYtd';
    $scope.searchStudent   = '';
    $scope.students = classData.getClassData(); //returns all 		data
	
//Controller 2: 

angular.module('attendanceApp')
  .controller('studentHistoryCtrl', function($scope, $stateParams, classData) {
    //get all  data
    $scope.students = classData.getClassData();
    console.log($scope.students); //returning an empty array


Solution

  • You must return your promise, otherwise your object is returned before the execution of the promise.

    angular.module('myApp')
        .factory('classData', function($http){
    
          return {
    
            getClassData : function() {
    
              var studentData = [ ];
    
              return $http({
                method: 'GET',
                url: 'theUrl'
              }).then(function(data){
                for(var i = 0; i < data.length; i++)
                  studentData.push(data[i]);
                return studentData;
              }, function(){
                alert("error", error);
              });
    
    
            }
          };
        });
    

    and then, in your controller, use your promise :

    classData.getClassData().then(function(results){
        $scope.students = result;
    });