-1

I am starting out with angular JS and I have created a factory with student data. The student data looks like the below.

{
    "male": [
        ["John", "Smith", "2000-10-10"],
        ["James", "Smith", "2000-10-10"]
    ]
}

I have a factory and a Controller setup as shown below

    .factory('Students', ['$http', function($http) {
        var data = {};
        return {
          getStudents: function () {
              $http.get('api/students.json').
              success(function(data, status, headers, config) {
                console.log(data.male); //returns the array of males
                data.studentlist = data.male;
                data.propertyOne = 'propertyOne'; //returns propertyOne but should also return in console.log(data) that I have further down the page.
                console.log(data.propertyOne);

               }).
              error(function(data, status, headers, config) {
                // log error
                console.log('error');
              });
              data.propertyTwo = 'propertyTwo';
              console.log(data); //returns propertyTwo

              return data;
          }
        }
    }]);

    .controller('StudentCtrl', ['$scope', 'Students',   
      function ($scope, Students) {
        $scope.students = Students.getStudents();
        console.log($scope); // only properyTwo is returned in the students scope
    }])

What I can not work out is how to get the data which gets loaded on success to be added to my data object? As you can see from my comments, I am returning data in my success but then it is no longer available outside of my sucess function? What do I need to change here to get this working so that in my controller I can access the student list returned from my students.json file.

ak85
  • 4,154
  • 18
  • 68
  • 113
  • 1
    There are numerous of these, here are some others.. http://stackoverflow.com/questions/12505760/processing-http-response-in-service, http://stackoverflow.com/questions/19121918/returning-response-data-from-http-in-angular-factory. Official documentation is pretty good as well. – PSL Oct 22 '14 at 01:38

1 Answers1

2

This is a timing issue. When console.log(data); //returns propertyTwo runs you still haven't made the assignment in the success callback yet. You have to move both into the success callback if timing is critical here.

I would recommend that you resolve the promise in the controller (add the success callback there instead of doing it in the service.

TGH
  • 38,769
  • 12
  • 102
  • 135