0

我已經定義了調用$http之前定義的變量ttest。 之後,我將數據分配給這個變量。http調用後的angularjs變量爲空值

ttest[0]具有價值$http功能,但外面有沒有可用的有值

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


    }); 
+0

響應包含什麼內容? –

+0

,因爲'$ http'是異步的 – mehulmpt

+0

嘗試在作用域上創建'ttest'作爲變量 –

回答

0

你正在做的HTTP請求是異步的,這意味着它是非阻塞。所以在發送請求之前,它下面的代碼會執行。做這樣的事情:

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 

    }); 

    }); 
0

在變量的JavaScript的範圍功能。由於then是回叫功能,所以ttest將不在範圍之外。

您可以在更新ttest變量的作用域之外創建函數,然後從回調函數中調用它。

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


    });