以 ng 重复显示字符串输出

Display string output in ng-repeat

本文关键字:字符串 输出 显示 ng      更新时间:2023-09-26

我想在视图中显示json对象。代码为:

<ul ng-repeat="item in items">
    <li ng-repeat="(key, val) in item">
        {{key}}: {{val}}
    </li>
</ul>

在,控制器:

$scope.init = function (){
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            $scope.items = JSON.parse(xhr.responseText);
            console.log(JSON.parse(xhr.responseText));
        }
    };
    xhr.open('GET', 'http://127.0.0.1:8000/user_list/', true);
    xhr.send(null);
}

控制台后.log我得到

[{"user_name": "Pranav", "user_id": 1}, {"user_name": "Sagar", "user_id": 2}]

我无法像前面的例子那样操作。

如何将其转换为格式:

$scope.items =
    [
        {"user_name": "Pranav", "user_id": 1},
         {"user_name": "Sagar", "user_id": 2}]
    ];

所以,我可以使用它。

您的数据格式正确,但是对 AJAX 请求使用 Angular 的$http,因为这将触发摘要周期并允许视图更新:

$http.get("http://127.0.0.1:8000/user_list/").success(function(data) {
    $scope.items = data;
});

我在这里创建了一个小提琴:http://jsfiddle.net/fynva/

我简化了示例中的 HTTPGET 调用,因为您在获取 JSON 时没有问题。下面是代码示例。

<div ng-app="myApp">
        <div ng-controller="TextController">
            <div>
                    <label for="spSelectViewMenu">Please select the list to view:</label>
                    <select id="spSelectViewMenu" ng-model="list" ng-options="c.user_name for c in lists"></select><br />
                <ul ng-show="list" ng-repeat="(key, val) in list" >
                    <li>{{key}} : {{val}}</li>
                </ul>
            </div>
    </div>
</div>
<script>
var myAppModule = angular.module('myApp', []);
myAppModule.controller('TextController', function ($scope) {
            $scope.lists = JSON.parse('[{"user_name": "Pranav", "user_id": 1}, {"user_name": "Sagar", "user_id": 2}]');
});
</script>