Angular ng-repeat中的Json字符串不起作用



我从$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 元素,但它现在不起作用。

对于角度中的 Json 解析,您必须在成功方法中使用以下代码。

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

JSON.parse 不应该正常工作吗?

$scope.artists = JSON.parse(data);

您的 html 中有错误,请尝试:

 <td> {({ fields.artist.link.})} </td>

而不是 artist.fields.link,根据您的 JSON : \"字段": {\"艺术家": \"达芬奇", \"链接\": \

最新更新