0

I am using Angularjs as frontend I have defined the variable ttest defined before $http call. after that i assign data to this variable .

the value ttest[0] has value in $http function but outside there is no value available there

angular.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
  .controller('AppCtrl', function($scope,$http,$log) {
    var imagePath = 'img/list/60.jpeg';

  var ttest=[];
var url = "https://www.w3schools.com/angular/customers.php";

$http.get(url).then(function(response) {
        ttest = response.data;
  $scope.messages =ttest
  $log.info(ttest[0]);

    });

  $log.info(ttest[0]);


  });
4
  • what does the response contains ? Commented Feb 27, 2017 at 5:41
  • because $http is asynchronous Commented Feb 27, 2017 at 5:42
  • try creating ttest as a variable on scope Commented Feb 27, 2017 at 5:42
  • Your code is correct can you add a console.log(response) in then function and tell me what you getting in response Commented Feb 27, 2017 at 5:46

3 Answers 3

1
//Check the below comment ,you will find out what are you doing wrong 
angular.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
  .controller('AppCtrl', function($scope,$http,$log) {
    var imagePath = 'img/list/60.jpeg';

  var ttest=[];
var url = "https://www.w3schools.com/angular/customers.php";

$http.get(url).then(function(response) {
  //      ttest = response.data;
        ttest = response.records; <-- change data to records
  $scope.messages =ttest
  $log.info(ttest[0]);

    });

  $log.info(ttest[0]);


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

Comments

0

The HTTP request you're making is asynchronous that means it is non blocking. So before your request is sent, the code below it executes. Do something like this:

angular.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
  .controller('AppCtrl', function($scope,$http,$log) {
    var imagePath = 'img/list/60.jpeg';

  var ttest=[];
var url = "https://www.w3schools.com/angular/customers.php";

$http.get(url).then(function(response) {
        ttest = response.data;
  $scope.messages =ttest
  $log.info(ttest[0]);

$scope.yourCallback(); // do whatever you want to do here in this function

    });

  }); 

Comments

0

In javascript scope of variable is functional. Since then is call back function , ttest wont be available outside of the scope.

You can create the function outside of the scope which updates ttest variable and call it from the then callback function.

Comments

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.