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.

2
  • can you add a fiddle] Commented Nov 17, 2015 at 9:28
  • could you also show us the specific error? Commented Nov 17, 2015 at 9:31

3 Answers 3

42

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

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

2 Comments

.success is deprecated. Use .then instead ;)
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.
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).

2 Comments

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
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.
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.