2017-09-13 90 views
1

我有一個國家的JSON文件,現在我在控制檯中獲取數據,但它沒有打印在html文件中。它顯示在控制檯中,但在html文件中沒有打印。 所以我可以在我的html文件中調用數據。 如何從json中使用http獲取數據在angularjs中

var app = angular.module("myApp", []); 
 
      
 
app.controller('myController', function($scope,$http) { 
 
    $http.get(".../../assets/json/country.json"). 
 
     then(function(data){ 
 
      var countryData = data; 
 
    var conData = countryData.data; 
 
    for(var i=0; i<conData.length; i++){ 
 
     $scope.countries = conData[i]; 
 
\t console.log($scope.countries.name+ " " +$scope.countries.code); 
 
    } \t \t \t \t 
 
     }) 
 
    });
<html> 
 
    
 
    <head> 
 
     <title>Angular JS Controller</title> 
 
     <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 
 
    </head> 
 
    <body> 
 
     <div ng-app="myApp" ng-controller="myController"> 
 
     <div ng-repeat="country in countries"> 
 
     {{country.code}} 
 
     {{country.name}} 
 
     </div> 
 
     </div> 
 
    </body> 
 
</html>
這是我country.json文件 輸入代碼在這裏 [ { 「名」: 「阿富汗」, 「代碼」: 「AF」 },{ 「名」:「奧蘭羣島 「 」代碼「: 」AX「 }, { 」名「: 」阿爾巴尼亞「, 」代碼「: 」AL「 }, { 」名「: 」阿爾及利亞「, 」 代碼「:」DZ「 }]

回答

2

現在您已注入$http服務到控制器中,我已經更新了我的答案...

我已經改變了你的回調代碼咯,最重要的變化是指$scope.countries到成功回調參數的data屬性(在下面的代碼中爲obj)。

app.controller('myController', function($scope,$http) { 

    $http.get(".../../assets/json/country.json").then(getCountriesSuccess); 

    function getCountriesSuccess(obj){ 

    $scope.countries = obj.data; // <--- This is the important line here! 

    $scope.countries.forEach(function(country){ 
     console.log(country.name + " " + country.code); 
    });    
    } 
}); 

這應該與你的HTML工作,因爲它已經表示:

<div ng-app="myApp" ng-controller="myController"> 
    <div ng-repeat="country in countries"> 
    {{country.code}} 
    {{country.name}} 
    </div> 
</div> 
+1

我已經加入了$ http和還得到在控制檯中的數據,但在HTML它不工作 – ns093

+0

@ ns093我已經更新答案。我已經稍微更改了代碼,希望它更簡潔一點。 –

+0

我得到了答案,如果我們在html中使用這樣的話,那麼它的工作,

{{country.name}}{{country.code}}
。這是工作100% – ns093

相關問題