1

I have a JSON file of country, Now I get the data in console but its not printing in html file. It's shown in console but in html file not printing. So how I can call data in my html file.

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>
It's my country.json file enter code here [ { "name": "Afghanistan", "code": "AF" }, { "name": "Åland Islands", "code": "AX" }, { "name": "Albania", "code": "AL" }, { "name": "Algeria", "code": "DZ" }]

1 Answer 1

2

Now that you are injecting the $http service into your controller, I've updated my answer...

I've changed your callback code slightly, the most important change is to point $scope.countries to the data property of the success callback parameter (obj in the code below).

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);
    });             
  }
});

That should work with your HTML as it already stands:

<div ng-app="myApp" ng-controller="myController">
  <div ng-repeat="country in countries">
    {{country.code}}
    {{country.name}}
  </div>
</div>
Sign up to request clarification or add additional context in comments.

3 Comments

i have added the $http and also get the data in console but in html it's not working
@ns093 I've updated the answer. I've changed the code slightly, hopefully it's a little more succinct.
i got the answer, if we are using like this in html then its work, <div ng-repeat="country in countries.data">{{country.name}}{{country.code}}</div>. It's work 100%

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.