MVC
MVC

Reputation: 679

How to access JSON object using AngularJS

I have stored JSON to separate file Countries.Json inside folder called ListofCountries in the View.

Now I want to display these data on button click using AngularJS.

But I am unable to pass JSON values into my code.

Please help me.

Countries.json

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

HTML Code

<!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>

Upvotes: 0

Views: 50

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222722

You need to access response.Countries not 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

Upvotes: 2

Related Questions