Search code examples
javascriptjsonangularjstextxmlhttprequest

Getting Json data from text file in AngularJS


I am new to AngularJS and trying to fetch JSON data from a text file:

Here is my HTML:

<div ng-controller="customersController as custCont"> 
  <ul>
    <li ng-repeat="x in names">
      {{ x.Name + ', ' + x.Country }}
    </li>
  </ul>
</div>

Whereas my controller is as given below:

app.controller( "customersController", function( $scope, $window) {
    $http({
        url: 'test.txt',
        dataType: 'json',
        method: 'POST',
        data: '',
        headers: {
            "Content-Type": "application/json"
        }

    }).success(function(response){
        $scope.names = response;
    }).error(function(error){
        $scope.names = 'error';
    });        

This doesn't show anything. Now if I replace the above http request with test.txt data assigned to $scope.names then it starts working: I mean, something like this:

$scope.names = [
{
"Name" : "Alfreds Futterkiste",
"City" : "Berlin",
"Country" : "Germany"
},
{
"Name" : "Berglunds snabbköp",
"City" : "Luleå",
"Country" : "Sweden"
},
{
"Name" : "Centro comercial Moctezuma",
"City" : "México D.F.",
"Country" : "Mexico"
},
{
"Name" : "Ernst Handel",
"City" : "Graz",
"Country" : "Austria"
},
{
"Name" : "FISSA Fabrica Inter. Salchichas S.A.",
"City" : "Madrid",
"Country" : "Spain"
},
{
"Name" : "Galería del gastrónomo",
"City" : "Barcelona",
"Country" : "Spain"
},
{
"Name" : "Island Trading",
"City" : "Cowes",
"Country" : "UK"
},
{
"Name" : "Königlich Essen",
"City" : "Brandenburg",
"Country" : "Germany"
},
{
"Name" : "Laughing Bacchus Wine Cellars",
"City" : "Vancouver",
"Country" : "Canada"
},
{
"Name" : "Magazzini Alimentari Riuniti",
"City" : "Bergamo",
"Country" : "Italy"
},
{
"Name" : "North/South",
"City" : "London",
"Country" : "UK"
},
{
"Name" : "Paris spécialités",
"City" : "Paris",
"Country" : "France"
},
{
"Name" : "Rattlesnake Canyon Grocery",
"City" : "Albuquerque",
"Country" : "USA"
},
{
"Name" : "Simons bistro",
"City" : "København",
"Country" : "Denmark"
},
{
"Name" : "The Big Cheese",
"City" : "Portland",
"Country" : "USA"
},
{
"Name" : "Vaffeljernet",
"City" : "Århus",
"Country" : "Denmark"
},
{
"Name" : "Wolski Zajazd",
"City" : "Warszawa",
"Country" : "Poland"
}
];

The text file obviously contains all the data except the first row (i.e. $scope.names = [ and the last semicolon;

That means the $http request to test.txt is failing which is in the same folder as HTML and JS files.


Solution

  • You are missing to define $http as a parameter

    app.controller( "customersController", function( $scope, $window, $http) {
    

    Also make sure you are testing in a web server. You cann't make ajax request from file:// protocol

    Also change your request from POST to GET and it should work fine. Here is a Punklr

     method: 'GET',