Reputation: 2597
I have json file in my file system. Is there any way to load content into variable?
I tried this:
vm.timeZones = require("timezones.json");
but it gives this error:
ReferenceError: require is not defined
Upvotes: 0
Views: 1779
Reputation: 48968
$http.get("timeZones.json")
.then(function onSuccess(response) {
// Handle success
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
//...
vm.timeZones = data;
})
.catch(function onError(response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
//...
});
For more infomation, see AngularJS $http Service API Reference.
Upvotes: 0
Reputation: 9133
jQuery.getJSON() should help.
Link for reference: JQuery.getJSON
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
function init() {
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
});
}
Upvotes: 2
Reputation: 943185
Probably not.
If you were reading the data over HTTP instead of directly from a filesystem then you could use the XMLHttpRequest object (or, in newer browsers, fetch) which Angular abstracts through $http
.
If you are using Firefox, then you can use that approach to read local files which are in the same directory (or a subdirectory of it) as the HTML document. Other browsers have stricter security rules.
If you allowed the user to select the file (via a <input type="file">
) then you could use the FileReader API.
Upvotes: 0