0

I have JSON file, contains I am loading JSON file using angular, I have what I think is probably a very obvious question, but I couldn't find an answer anywhere, I have referenced a few topics here, but there is still no pp to solve my problem I am just trying to load some JSON data file using angular, but its not follow expected

   <body>
    <h1>Sample Application</h1>
    <div ng-app="app">
    <div ng-controller="controller">
        <p>Enter your Name:
            <input type="text" ng-model="name">
        </p>
        <p>Hello <span ng-bind="name"></span>!</p>
        <p>List of Countries with locale:</p>
        <ol>
            <li ng-repeat='country in countries '>
                {{ country.name }}
            </li>
        </ol>
    </div>
   </div>
  <script src="libs/angular.js"></script>
  <script src="script/jsonRead.js"></script>
   </body>

Every example of Angular only shows stuff like this:

var jsonRead = angular.module('app', []);
 jsonRead.controller('controller', function($scope,$http){
    $scope.countries=null;
    $http.get("countries.json").success(function(result){
        $scope.countries = result;  
    }).error(function(result) {
        /* Act on the event */
        console.log("there was an error");
    });

 });

and json file:

 {
    "countries":[
     {
        "locale":"en-US",
        "name":"United States"
     }, 
     {
        "locale":"en-GB",
        "name":"United Kingdom"
     },
     {
        "locale":"en-FR",
        "name":"France"
     }
    ]
   }

The problem is that I cannot load code from other pages into contries.json file Not only does this controller code not work, but it breaks my $contries code and makes the html actually display my raw angular variables.

Sky Tử
  • 1
  • 2

2 Answers2

1

You have to use this:

var jsonRead = angular.module('app', []);
 jsonRead.controller('controller', function($scope,$http){
    $scope.countries=null;
    $http.get("countries.json").success(function(result){
        $scope.countries = result.data; // <----it should be like this  
    }).error(function(result) {
        /* Act on the event */
        console.log("there was an error");
    });

 });

and in the view you have to update to this:

<li ng-repeat='country in countries.countries '>

or if i have to update your code then atleast you have to do this:

$scope.countries = result.data.countries;
Jai
  • 74,255
  • 12
  • 74
  • 103
0

you may check resource variable by $http and get. Is it post or get? Are you sure the second snippet is right? Also check this How to load json into my angular.js ng-model?

Community
  • 1
  • 1