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
-
What if you try setting the scope variables inside the success function? I bet this is an async issue.bencripps– bencripps2014年08月22日 18:40:40 +00:00Commented Aug 22, 2014 at 18:40
1 Answer 1
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.
2 Comments
resolve in ngRoute of uiRouter.