A. Dziedziczak A. Dziedziczak - 1 month ago 6
AngularJS Question

How to assign scope variable inside function that returns data from server?

I have a function that is in angular controller.

scope.asyncInit
is called at the end of controller. It is a function that inits data for view.



scope.asyncInit = function() {
scope.phoneData;
dsc.In('module-agreements-lists').run('select_agreements_by_value').now('phone').then(function(res) {
scope.phoneData = res.result;
});
};



I should return data from database and asing it to scope.phoneData variable.

The problem is that when i use it like this:



scope.asyncInit = function() {
scope.phoneData;
dsc.In('module-agreements-lists').run('select_agreements_by_value').now('phone').then(function(res) {
scope.phoneData = res.result;
console.log(scope.phoneData);
});
};



It shows the data that are returned from the server in console log but they are not visible outside the
dsc.In('module-agreements-lists').run('select_agreements_by_value').now('phone').then(function(res) ...
.

The console log that's in the code below returns to console log scope.phoneData as undefined.



scope.asyncInit = function() {
scope.phoneData;
dsc.In('module-agreements-lists').run('select_agreements_by_value').now('phone').then(function(res) {
scope.phoneData = res.result;
});
console.log(scope.phoneData);

};



Am i missing something important here? I have no idea why it's not working properly.

Answer

It is because that is an Asynchronous call.
An asynchronous call to the server will just run, and not wait for success.
So the code goes on, even if you did not get the data yet.

You use .then() function to do stuff that you want to be called after success.

Thats why it logs 'undefined' in the second method. The data did not arrive from the server yet.

Comments