0

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>
2
  • Console the value of myData Commented Jul 1, 2018 at 2:22
  • And post the output Theb it will easy to answer, what it returns in.response.data.records ? Commented Jul 1, 2018 at 2:25

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your demo. But currently I am getting error Failed to load resource: the server responded with a status of 404 (Not Found) I am not getting Json file loaded. It i under shared folder in my MVC application.
which means your json path is wrong, check the path . mark if the answer helped
I will try to fix it. One more help, the Json data should display only on button click in view. So appreciated if you could add that part as well.
I do not understand one thing why this is giving me error. GET http://localhost:62634/Test/Views/Countries.json 404 (Not Found). As the Json is under Views.
may be you can alter the path on the browser and see

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.