-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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.