23

I want to fetch data from JSON file which is on my local machine. But I am not able to get the data. It is showing some cross domain error for $http.

Here is my code.

angular.module('myApp',[])
  .controller('myCtrl', function ($scope, webtest) {
     webtest.fetch().then(function (data) {
         $scope.accounttype = data;
     })
});

.factory('webtest', function($q, $timeout, $http) {
    var Webtest = {
        fetch: function(callback) {
            return $timeout(function() {
                return $http.get('webtest.json')
                .then(function(response) {
                      return response.data;
                });
            }, 30);
         }
    };
    return Webtest;
}); 

Anyone please help me how to display data from local JSON file? Thanks in Advance.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Amit
  • 377
  • 2
  • 3
  • 12

3 Answers3

41

It's very simple like

$http.get('phones/phones.json').then(function(response) {
   $scope.phones = response.data;
});

Refer:http://stackoverflow.com/questions/21589340/read-local-file-in-angularjs

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Arun
  • 1,177
  • 9
  • 15
  • 4
    .success is deprecated. Use .then instead ;) – LOTUSMS Apr 03 '17 at 13:50
  • Unless and until the site is hosted on a local server, i don't think this should work. Please make sure you host your project on a local server and then access the .json file. It is then that the code should work fine. – Gurunath Rao Dec 18 '21 at 11:00
3

Don't you have an error message like "$http: is not defined" ?

I tried with a controller, this is working :

var ngApp = angular.module("ngApp", []);

ngApp.controller('myController', ['$http', function($http){
  var thisCtrl = this;

  this.getData = function () {
  this.route = 'webtest.json';
  $http.get(thisCtrl.route)
    .success(function(data){
      console.log(data);
    })
    .error(function(data){
      console.log("Error getting data from " + thisCtrl.route);
    });  
  }
}]);

If you haven't, use web developer tools (Ctrl+Shift+I in firefox).

Pico12
  • 1,229
  • 12
  • 18
  • 1
    I am getting this Error-> XMLHttpRequest cannot load file:///C:/Users/Handson/webtest.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource – Amit Nov 17 '15 at 15:21
  • I guess it's because you don't have the right to access local files (security reason). You should use a local web server (like apache) to avoid this kind of error. – Pico12 Nov 18 '15 at 12:15
2

If you haven't already done so. Try setting up a crossdomain policy for your application.

Hardik Patel
  • 3,868
  • 1
  • 23
  • 37