0

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.

1 Answer 1

1

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.

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

6 Comments

So when console.log inside the function displays the data that are the one that are returned from the server and in case when the console.log is outside the function it displays undefined because the data are not yet in the browser. But how to make it works? Even if the function returns data after some time they are not displayed in the view. I have no idea how to make it work.
@A.Dziedziczak is the view bound to scope.phoneData?
Yes it is: <div data-ng-repeat="con in phoneData"> ... </div>
@A.Dziedziczak try add scope.$apply(); after you assign the data
I'm sorry your solution works perfectly! It was my fault that it was not working. I add wrong models in the ng-repeat so nothing was displayed ... I'm sorry for wasting your time. I'll accept your answer as the right one. Again sorry for trouble..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.