0

I'm attempting to load a JSON file into my JavaScript file. However, I am at a loss at how to do so.

My app.js file:

var myApp = angular.module('myApp', []);

myApp.controller('MainCtrl', ['$scope', function ($scope) {
    console.log("in here");
    var jsonData = require('../test_data.json'); 

    console.log(jsonData);
}]);

I have a test_data.json file in my project directory. The error above gives a "require is not defined", so it seems that I must install RequireJS? Is there another way to do so without installing any plugins?

fibono
  • 773
  • 2
  • 10
  • 23

1 Answers1

3

Try using Angular's $http service and you'll have more control over the loading, errors, etc:

myApp.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
  console.log("in here");
  $http.get('../test_data.json').success(function(data) {
    console.log(data);
  })
}]);
anthumchris
  • 8,245
  • 2
  • 28
  • 53
  • Thanks for the prompt response, but I got this error: `XMLHttpRequest cannot load file:///{file_path_here}. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.` – fibono Jun 24 '15 at 17:07
  • You'll need to run it over `http://...` (locally or remotely). Or disable Chrome's security via http://stackoverflow.com/questions/4819060/allow-google-chrome-to-use-xmlhttprequest-to-load-a-url-from-a-local-file – anthumchris Jun 24 '15 at 17:09
  • You have to run your app on an app server which supports http calls – Sudhansu Choudhary Jun 24 '15 at 17:09
  • @SudhansuChoudhary, what's the fast way to do this? I don't have AngularJS "installed," as I include it in my html file with a script tag pointing to Google CDN. – fibono Jun 24 '15 at 17:26
  • 1
    there is nothing as a faster way. And you dont need to install AngularJS, your CDN is fine. But when you use `http` protocols, you got to have a Web Server which would handle these calls. You got to install those servers, e.g., Apache Web Server, Apache Tomcat, Nginx etc. You got to install these not AngularJS. Check this, http://www.webdevelopersnotes.com/hosting/list_of_web_servers.php3 – Sudhansu Choudhary Jun 24 '15 at 17:36
  • try once with @Chris's suggestion about disabling Chrome's security, that should work And also how does the json file get generated? Where do you fetch it from? You can hardcore those val – Sudhansu Choudhary Jun 24 '15 at 17:39