2016-01-30 36 views
0

我想将angular.js包含到我正在处理的项目中。我对角度很陌生。 Angular似乎没有阅读我的json文件,我不知道我做错了什么。我在下面创建了一个测试文件,模仿我在较小规模上做的事情。如果任何人都可以向我解释我做错了什么,那将非常感激。Angular.js不能读取json文件

的index.html

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset = "UTF-8"> 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
    <script src='app.js'></script> 
    <script src='MainController.js'></script> 
    <title>angular test</title> 
</head> 
<body> 
    <h1>Angular Test</h1> 
    <div ng-app = 'myApp' ng-controller='MainController'> 
     <p>{{myData}}</p> 
    </div> 

</body> 

controller.js

app.controller('MainController', function($scope, $http) { 
    $http.get("data.json").then(function(response) { 
     $scope.myData = response.data.test; 
    }); 
}); 

app.js

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

data.json

{ 
    "test":"This data is from a json file" 
} 
+0

什么错误?它似乎在哪里发生? –

+0

看起来像一个CORS(跨源资源共享)的问题...可能会检查出[这篇文章](http://stackoverflow.com/questions/16930473/angularjs-factory-http-get-json-file) – sfletche

+1

似乎工作正常,请检查[this plunk](https://plnkr.co/edit/WT3bNO1rZMgjHrJMVUoN?p=preview)。也许有关于如何服务该json文件的服务器问题。浏览器开发工具中的网络选项卡显示了有关此调用的信息? – scniro

回答

0

路由原因是在data.json文件中添加的注释,请删除以下内容。

/* 
Project: angular test 
File: data.json 
Author: David Sanders 
Date: 
Comments: 
Kudos: 
Notes: site data 
*/ 

JSON文件不应该包含像这样的任何注释,因此JSON parson失败。

只要穿上,

{ 
    "test":"This data is from a json file" 
} 
+0

我没有意识到你不能把评论放在json文件中。什么是最基本的错误。现在工作得很好。 –