1

I have a really weird issue with my javascript page :

    $scope.ptfs = new Array();

    $http.get('trades.json').success(function(data) {
            data.portfolios.forEach(function(p){
                $scope.ptfs.push(new Portfolio(p.id , p.name));

                $scope.message3 = $scope.ptfs[0];

            })
    })

    $scope.message2 = $scope.ptfs;
    $scope.message4 = $scope.ptfs[0];

And the HTML :

2 : {{message2}}<br>
3 : {{message3}}<br>
4 : {{message4}}<br>

The result i got is : 2 : [{"id":0,"name":"CAN REAL","trades":[]},{"id":1,"name":"INVESTOPEDIA","trades":[]}] 3 : {"id":0,"name":"CAN REAL","trades":[]} 4 :

Any idea why : - $scope.message3 = $scope.ptfs[0]; AND - $scope.message4 = $scope.ptfs[0];

doesn't return the same result ?

Thanks, Nicolas

1
  • What if you try setting the scope variables inside the success function? I bet this is an async issue. Commented Aug 22, 2014 at 18:40

1 Answer 1

2

The issue you encounter is due to the asynchronous nature of your code. $scope.message4 = $scope.ptfs[0]; is executed before items get pushed to $scope.ptfs. At the time of assigning message4, your array is empty.

$http.get('trades.json') returns a promise. Once that promise is resolved, ie. once the server responds to your request, the callback of the then function is executed $scope.ptfs is populated.

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

2 Comments

thanks.Any way to go around that ? Except to put all the code inside the .success ?
It all depends on what you want to achieve. You can force to delay the instantiation of your controller until the data requested to the server is available. This can be achieve using resolve in ngRoute of uiRouter.

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.