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?

1 Answer 1

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);
  })
}]);
Sign up to request clarification or add additional context in comments.

6 Comments

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.
You'll need to run it over http://... (locally or remotely). Or disable Chrome's security via stackoverflow.com/questions/4819060/…
You have to run your app on an app server which supports http calls
@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.
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, webdevelopersnotes.com/hosting/list_of_web_servers.php3
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.