Access JSON file in Angular.js

All we need is an easy explanation of the problem, so here it is.

I want to access json file in angular.js by using the following code but I am unable to access the code because of the below mentioned shown error.
Help would be appreciated.!!

module :

angular.module("demoApp", ['demoApp.factory','demoApp.controllers']);

Factory:

angular.module('demoApp.factory', []).
factory('getJsonDataFactory',function($http){
    return{
    getData : function() {
        return $http.get('mapData.json');
    }
 }
});

controller :

angular.module('demoApp.controllers', []).
  controller('GetJsonController', function($scope,$http,getJsonDataFactory) {
              $scope.markers = [];  
              getJsonDataFactory.getData().success(function(data){
                $scope.photos=data;
            });
        });

Error :
In firefox:

 "Access to restricted URI denied" code: "1012"


return logFn.apply(console, args)

In Chrome :`

Origin null is not allowed by Access-Control-Allow-Origin.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

In fact i think you don’t have a server.

So, you’re getting your application through the file:// protocol.

But file:// protocol can’t do http get methods for security reasons.

To solve your matter i suggest you to put your application on a simple web server (like Apache, or wamp, xamp, lamp etc) or better to use grunt to build your application and run it on a test server through node.js

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply