我从$http请求中获得了一个json字符串,并希望使用ng-repeat来显示数据。现在,我从服务器获得了json字符串,但是ng-repeat没有把数据放到dom上。
<div ng-controller="mycontroller2">
<form ng-submit="submit()">
{% csrf_token %}
Search:<input ng-model="artiste" />
<input type="submit" value="submit" />
</form>
<table ng-repeat="artist in artists">
<tr>
<td> {({ artist.fields.link })} </td>
</tr>
</table>
</div>
<script>
artApp.controller('mycontroller2', ['$scope', '$http',
function($scope, $http){
$scope.submit = function(){
var call = {
method: 'POST',
url: '/rest/',
data: {
"artiste": $scope.artiste
},
headers: {
'Content-Type': 'application/json',
'X-CSRFTOKEN': "{{ csrf_token }}"
}
};
$http(call)
.success(function(data){
$scope.artists = data;
})
}
}]);
devtools中显示的响应数据是一个json字符串
"[{\"fields\": {\"artist\": \"Leonardo da Vinci\", \"link\": \"https://trove2.storage.googleapis.com/leonardo-da-vinci/galloping-rider-and-other-figures.jpg\", \"title\": \"Galloping Rider and other figures\"}, \"model\": \"serve.art\", \"pk\": 63057},我以为我可以用ng-repeat遍历它,并用数据生成html元素,但现在不起作用。
发布于 2014-12-04 20:27:38
对于angular中的Json解析,您必须在success方法中使用以下代码。
.success(function(data){
var response=angular.fromJson(data);
$scope.artists = response.fields;
}) 如下所示修改您的<table>,因为您已经将响应数组分配给了$scope.artists。
然后,您可以将您的json数据与单独的键一起使用。
<table ng-repeat="artist in artists">
<tr>
<td>{{artist.link}}</td>
</tr>
</table>在控制台中查看数值是否正在获取。
.success(function(data){
var response=angular.fromJson(data);
$scope.artists = response.fields;
console.log("artist :"+$scope.artists.artist);
console.log("link :"+$scope.artists.link);
})发布于 2014-12-04 20:25:30
难道JSON.parse不应该只是工作吗?
$scope.artists = JSON.parse(data);发布于 2014-12-05 05:06:35
您的html中有一个错误,请尝试:
<td> {({ fields.artist.link.})} </td>而不是根据你的json:\“artist.fields.link \”:{\"artist\":\“莱昂纳多·达·芬奇\”,\“链接\”:\
https://stackoverflow.com/questions/27293877
复制相似问题