Search code examples
javascriptangularjsangularjs-directiveangularjs-scope

Why Do i get null value in angularjs variable after http


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]);


  });

Solution

  • //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]);
    
    
      });