I
I
Ilya2015-01-29 22:57:37
JavaScript
Ilya, 2015-01-29 22:57:37

Why is the array of objects not visible (undefined) in the method?

There is this code:

chill.controller('messagesController', function($scope, $http, $rootScope, $location, $stateParams, $ionicSlideBoxDelegate, $ionicLoading) {

  if ($rootScope.userData != undefined) {
    $ionicLoading.show({
      template: 'loading'
    })
    $http.get('http://site/api/v1/messages/index/id_user/'+$rootScope.userData.id_user+'/id_contact/'+$stateParams.id)
    .success(function(data)	{
      $scope.messages = data;
      for (var i = 0; i < $scope.messages.response.length; ++i) {
        if ($scope.messages.response[i].type == 'location') {
          var strings = $scope.messages.response[i].content.split(' ');
          var lat1 = strings[0], lat2 = strings[1];
          $http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat1+','+lat2+'&sensor=false')
          .success(function(data)	{
            $ionicLoading.hide();
            $scope.messages.response[i].address = data.results[0].formatted_address;
          });
        };
      };
      $ionicSlideBoxDelegate.update();
    });
  }
  else
  {
    $location.path('/login');
  };
});

Question. Why is the $scope.messages array of objects not visible(undefined) in .success(function(data){} ?
Thanks.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ilya, 2015-01-29
@FireGM

success is only executed if $http.get is successful. You make an alert for a mistake. Will help.

D
Dmitry Demin, 2015-01-29
@keksmen

I propose to declare all model variables in advance (the same null).
The data from this will not appear faster, but the errors "such and such a key was not found in the scope object" will disappear forever.

S
sdo, 2015-01-30
@sdo

It seems that here is the processing you need
You were correctly told in the previous solution - the code is divided into several execution contexts. What is available in one context is not visible in another. The solution is to either forward the object you need to the context after the get is completed explicitly (but I don’t know if and how to do this in angular, you need to test it with simple examples first, I didn’t work with angular), or make requests asynchronous, so that you explicitly wait when each is executed in turn, and sequentially process their results - then there will be one sequential execution context. The last option is clearer, but longer. The first implies that the array may be in limbo for some time - half of the requests have been executed and added additional. information in the relevant objects, and half is still in the process of obtaining data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question