简体   繁体   中英

Variable scope issue with AngularJS

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM