user3574939 user3574939 - 3 months ago 14
AngularJS Question

angular.fromJson parsing local json file not working

I have a local json file (data.json) that I am attempting to parse using angular.fromJson which I don't have much familiar using. I've been following this post How do I update/add to a json file. My data.json file is in the same folder as my app.js file yet I am receiving a 404 error message 'localhost:3000/data.json 404 (Not Found)', which makes sense because data.json is not at that address it's at localhost:3000/apps/javascripts/data.json. Do I have to use an absolute url? However when I place data.json directly into angular.fromJson it works.

This works:

$scope.menu = angular.fromJson('{
"name": "Mark",
"id": 1,
"project": "AMI",
"project start": "10/1/2007",
"project end": "9/31/2008"
},
{
"name": "Ann",
"id": 2,
"project": "CLN",
"project start": "10/1/2007",
"project end": "9/31/2009"
},
{
"name": "Mary",
"id": 3,
"project": "CAN",
"project start": "10/1/2008",
"project end": "9/31/2011"
}');
console.log($scope.menu);
});


This doesn't work:

$http.get('data.json').success(function(data){
$scope.menu = angular.fromJson(data.menu);
console.log($scope.menu);


data.json script:

{
"menu": [
{
"name": "Mark",
"id": 1,
"project": "AMI",
"project start": "10/1/2007",
"project end": "9/31/2008"
},
{
"name": "Ann",
"id": 2,
"project": "CLN",
"project start": "10/1/2007",
"project end": "9/31/2009"
},
{
"name": "Mary",
"id": 3,
"project": "CAN",
"project start": "10/1/2008",
"project end": "9/31/2011"
}
]
}

Answer

Try changing the line

$http.get('data.json').success(function(data){

to

$http.get('/apps/javascripts/data.json').success(function(data){.