angular.fromJson解析本地json文件无效

时间:2016-08-20 01:01:44

标签: angularjs json parsing

我有一个本地json文件(data.json),我试图使用angular.fromJson解析,我不太熟悉使用它。我一直在关注这篇文章How do I update/add to a json file。我的data.json文件与我的app.js文件在同一个文件夹中但我收到404错误消息'localhost:3000 / data.json 404(Not Found)',这是有道理的,因为data.json不在那里解决它在localhost:3000 / apps / javascripts / data.json。我必须使用绝对网址吗?但是,当我将data.json直接放入angular.fromJson时,它可以工作。

这有效:

$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);
        });

这不起作用:

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

data.json脚本:

{   
"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"
    }
    ]
}

1 个答案:

答案 0 :(得分:1)

尝试更改行

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

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