如何使用AngularJS访问JSON对象

时间:2018-07-01 01:14:50

标签: html angularjs

我已将JSON存储到视图中名为Countries.Json的文件夹内的单独文件ListofCountries中。

现在,我想使用AngularJS在单击按钮时显示这些数据。

但是我无法将JSON值传递到我的代码中。

请帮助我。

Countries.json

{
  "Countries": [
    {
      "Country": "USA"
    },
    {
      "Country": "Australia"
    },
    {
      "Country": "Canada"
    },
   {
      "Country": "UK"
    }
  ]
}

HTML代码

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="countriesCtrl"> 

<ul>
  <li ng-repeat="x in myData">
    {{ x.Country }}
  </li>
</ul>
<input type="button" id="list-btn" value="List Data"/>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('countriesCtrl', function($scope, $http) {
  $http.get("Countries.Json").then(function (response) {
      $scope.myData = response.data.records;
  });
});
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:2)

您需要访问 response.Countries 而不是 response.data.records

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
  $http.get("Countries.json")
  .success(function (response) {$scope.code = response.Countries;})
  .error(function (response) {alert("Error")})
});

WORKING DEMO