我有一个国家的JSON文件,现在我在控制台中获取数据但不在html文件中打印。它在控制台中显示但在html文件中不打印。 所以我如何在我的html文件中调用数据。
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];
console.log($scope.countries.name+ " " +$scope.countries.code);
}
})
});
<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>
答案 0 :(得分:2)
既然您正在将$http
服务注入您的控制器,我已经更新了我的答案......
我稍微更改了您的回调代码,最重要的更改是将$scope.countries
指向成功回调参数的data
属性(以下代码中的obj
)。< / p>
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>