简体   繁体   中英

Cannot access $scope variable with angular js

I have a code piece of this:

$scope.getPlaylists = function() {
    Restangular.all('getPlaylists').getList().then(function(getPlaylists){
          var plist;
              console.log("getplists: "+getPlaylists);
          for(var i=0; i < getPlaylists[0].length; i++) {
              plist = getPlaylists[0][i];
              $scope.playlists.push(plist);
              console.log("inside loop: "+$scope.playlists.length);
          }
              console.log("loop end: "+$scope.playlists.length);
          });
    console.log("total length: "+$scope.playlists.length);
};

Inside and just after the loop, I can see the length of the playlists in the console, but total length: is seen zero. What should I do so that I can access the $scope.playlists.length with the correct value?

You're logging the values after an async call ( getList ) - put the log statement within the callback or pass your data to a callback function and do the work there.

Restangular.all('getPlaylists').getList().then(function(getPlaylists){
    //all work pertaining to the info received has to be done here
    //Or an external callback function    
});
//Code here does not know about received data from the async call - it's still in progress

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