如何在Angular中将post数据绑定到ng repeat

时间:2017-04-30 11:26:47

标签: angularjs

var app = angular.module("newmodule", []).controller("myController", function ($scope,$http,$log) {
            $.ajax({
                type: "GET",
                url: "/Home/EmployeeDetails",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    $scope.$apply(function () {
                        $scope.employees = response;
                    }) 
                },
                error: function () { alert("failure"); }
            });
    });

然而,数据没有被绑定,但我得到的数据是响应。

<div ng-controller="myController" style="margin-top:5%;margin-left:5%">
    <table class="table-responsive table-condensed table-bordered" style="margin-top:3%">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Company</th>
                <th>Location</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="emp in employees">
                <td>{{ emp.Id }}</td>
                <td>{{ emp.Name }}</td>
                <td>{{ emp.Company }}</td>
                <td>{{ emp.Locaion }}</td>
            </tr>
        </tbody>
    </table>

</div>

4 个答案:

答案 0 :(得分:0)

使用$http代替ajax

var app = angular.module("newmodule", []).controller("myController", function($scope, $http, $log) {

    $http({
        url: "/Home/EmployeeDetails",
        method: "GET"
    }).then(function(response) {
        $scope.employees = response.data;
    }).catch(function(response) {
        alert("failure");
    })
});

答案 1 :(得分:0)

我可以尝试,两者都有效。我认为你的问题在哪里......

"use strict";

angular.module("HttpDemo", [])
  .controller("HttpDemo", MainController);

function MainController($scope, $http) {
  $http.get("https://jmgen.herokuapp.com/")
  .then(function(response) {
    $scope.httpResult = response.data;
  })
  $.ajax({
    type: "GET",
    url: "https://jmgen.herokuapp.com/",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
      $scope.ajaxResult = response;
    },
    error: function () {
      alert("failure"); }
    });
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div ng-app="HttpDemo" ng-controller="HttpDemo">
  $http: {{httpResult | json}}<br />
  $.ajax: {{ajaxResult | json}}
</div>

答案 2 :(得分:0)

  

尝试将ng-repeat放入tbody中:

onMessageReceived

`

答案 3 :(得分:0)

使用$ http服务而不是$ ajax。并通过console.log(响应)在控制台上打印响应; 并研究响应的结构,因为响应有两个关键的“元”和“数据”。通过在控制台上打印响应,您将找到数据的位置。 例如,通常数据存在于数据密钥下。所以试试“employees = response.data”。