angular.js - 如何用angularjs读取本地json?

浏览:24日期:2023-02-06

问题描述

我读取了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:

<p ng-controller='dataController' ng-repeat='x in data|filter:{status:’0’}'><p id='{{x.id}}'><img ng-src='https://www.6hehe.com/wenda/{{x.imgurl}}' /></p></p>

问题解答

回答1:

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

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

应该这样取:

function dataController($http,$scope) { $http.get('json/text.json').success(function(data) { $scope.data = data.freetrial; }); }回答2:

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

回答3:

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

回答4:

问下你取出来了吗?我一直取不出来

回答5:

如果是404错误的, 就是get的json数据没有获取到, 也就是json的路径出现了问题, 你的代码我拷贝试了一下, 发现路径对的前提下, 数据也不会显示在页面上.但是:

function dataController($http,$scope) {$http.get('json/text.json').success(function(freetrial) { alert(freetrial);$scope.data = freetrial;console.log($scope.data);//可以打印出数据 });};

正确的get方法应该:

function dataController($http, $scope) { $http.get('rightUrl').success(function(data) {$scope.data = data.freetrial; });};

data的作用:参照angular.js源代码

$http.get(’test_data.json’, {cache: $templateCache}).success(function(userComments){ self.userComments = userComments; });

相关文章: