0

In my controller I call a factory that returns a JSON object as such:

function getData() {
    trainDataFactory.getData()
        .success(function (data) {
            $scope.dataList = data;
        })
        .error(function (error) {
            $scope.status = 'Unable to load data: ' + error.message;
        });
}

I am then able to access $scope.dataList in the view like so (which works):

{{ dataList[0].UnitNumber }}

But I want to access this same variable in the controller however it won't work - angular just breaks.

I try this at the start of the controller:

init();
function init() {
    getData();

    console.log($scope.dataList[0].UnitNumber);

    $scope.firstDataListItem = $scope.dataList[0].UnitNumber;
}

getData() is called so I don't see why $scope.dataList is unavailable??

JLRishe
  • 99,490
  • 19
  • 131
  • 169
Jack
  • 319
  • 6
  • 16
  • Can you post the whole controller? You're probably doing something wrong with the inclusion of the $scope element and reaching the getData() method from the inner scope of the controller. – downhand Jan 22 '15 at 10:57

1 Answers1

3

The data retrieval in getData() is going to execute asynchronously. It's not going to be available the moment getData() is done executing.

You need to make use of promises:

function getData() {
    return trainDataFactory.getData()
    .then(function (response) {
        return response.data;
    })
    .catch(function (error) {
        throw new Error('Unable to load data: ' + error.message);
    });
}

function init() {    
    getData().then(function (data) {
        $scope.dataList = data;
        console.log(data[0].UnitNumber);
        $scope.firstDataListItem = data[0].UnitNumber;
    })
    .catch(function (error) {
        $scope.status = error.message;
    });
}
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Thank you, this works. So, when working asynchronously the then statement is important to access the data directly after retrieving it? – Jack Jan 22 '15 at 11:15
  • Also, does this mean to use dataList you must access it either in getData().then(function (data) { } or outside of the init() function? – Jack Jan 22 '15 at 11:35
  • @JakkyD Yes, promises and the `then()` method are very important for asynchronous tasks. I recommend reading [this book](https://github.com/getify/You-Dont-Know-JS/tree/master/async%20%26%20performance) when you have the time. I don't entirely understand your second question, but generally, you should be doing asyncrhonous tasks inside a `then()` handler _somewhere_. – JLRishe Jan 22 '15 at 11:39