如何用angularjs读取本地json?


我读取了text.json,并且赋值到$scope.data里了,在html中用ng-repeat没有反应。请问怎么样才能让读取出来的数据分别写到html页面里对应的位置去?
ps:这段代码运行时报错说,找不到json文件的路径404.
js:


 function dataController($http,$scope) {
 $http.get("json/text.json").success(function(freetrial) { alert(freetrial);$scope.data = freetrial;});

json里的数据:


 {"freetrial":[{
"id": "01",
"imgurl": "images/1.jpg",
"status": "0"
},
{
"id": "02",
"imgurl": "images/2.jpg",
"status": "1"
}
]}

html:


 <div ng-controller="dataController" ng-repeat="x in data|filter:{status:'0'}">
<div id="{{x.id}}">
<img ng-src="{{x.imgurl}}" />
</div>
</div>

json angularjs

无节操的右脚 10 years, 10 months ago

你可以先配绝对路径,如果成功说明没其他问题的时候,再换相对路径。

shewing answered 10 years, 10 months ago

你可以先配绝对路径,如果成功说明没其他问题的时候,再换相对路径。

pptp1 answered 10 years, 10 months ago

既然已经提示404了,也就是没找到 json 咯,应该是路径错误

还有你的 success() 方法里面的 freetrial 实际上代表的是json的所有数据,所以你后面要取那个数组的时候这样是取不到的。

应该这样取:


 function dataController($http,$scope) {
     $http.get("json/text.json").success(function(data) {
         $scope.data = data.freetrial;
     });
 }

霧雨魔里莎 answered 10 years, 10 months ago

Your Answer