使用ng-repeat显示从数据库中获取的json数据

时间:2014-05-26 10:18:39

标签: javascript json angularjs

我已经实现了一个流程,使用以下方法在#showdata div中显示数据库中的数据。

function UserCntrl($scope) {

getUser();

$scope.save = function () {
    $.ajax({
        type: "POST",
        url: "UserService.asmx/InsertUser",
        data: "{'Username':'" + $scope.Name + "','Email':'" + $scope.Mail + "','Password':'" + $scope.Password + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            alert(msg.d);
            $("#showdata").append("Username: " + $scope.Name + "<br />" + "Email:" + $scope.Mail + "<br />");
        },
        error: function (msg) {
            alert(msg.d);
        }
    });
};

function getUser() {
    $.ajax({
        type: "POST",
        url: "UserService.asmx/GetUserDetails",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var parsed = $.parseJSON(data.d);
            $.each(parsed, function (i, jsondata) {
                $("#showdata").append("Username: " + jsondata.Name + "<br />" + "Email:" + jsondata.Mail + "<br />");
            });
        },
        error: function (XHR, errStatus, errorThrown) {
            var err = JSON.parse(XHR.responseText);
            errorMessage = err.Message;
            alert(errorMessage);
        }
    });
  };
}

一切正常,所有数据都在#showdata div中正确显示。但现在我想做同样的事情,但是使用ng-repeat指令。

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:1)

正如RGraham所说,使用HTTP请求不是“有条不紊的方式”,但作为一个起点,这是一个有效的例子:

JS:

function EntryCtrl ($scope, $http) {
    $scope.rootEntry = [];
    $http.get('https://api.github.com/users/mralexgray/repos').success(function(root) {
        $scope.rootEntry = root;
    });
}

HTML:

<div ng-controller="EntryCtrl">
    <ul>
        <li ng-repeat="root in rootEntry">{{root.name}}</li>
    </ul>
</div>

实例:http://plnkr.co/edit/Grlgfob6tjE63JizWdCD?p=preview

答案 1 :(得分:0)

$ scope.data = object

<tr ng-repeat="(key, value) in data">
      <td> {{key}} </td> <td> {{ value }} </td>
</tr>

答案 2 :(得分:0)

假设'parsed'在您的控制器的$ scope属性

<div id="showdata">
    <div ng-repeat="(i, jsondata) in parsed" >{{"Username: " + jsondata.Name + "<br />" + "Email:" + jsondata.Mail + "<br />"}}</div> 
</div>