【问题标题】:How to print data in html using ng-repeat angularjs如何使用 ng-repeat angularjs 在 html 中打印数据
【发布时间】:2016-03-10 08:55:07
【问题描述】:

我在控制器中有 json 数据作为响应。我必须在 html 中打印该数据。

为此我做了如下:

在我的控制器中

.controller('DataImportControl', ['$scope','$http', '$location', '$rootScope' , function($scope, $http, $location, $rootScope) {

    console.log(" In dataimportCtrl");

        $scope.readCustomer = function(){

            console.log("in read customer");

            $http.post('/custimport').success(function(response) {


                console.log("in controller");
                console.log("controller:"+response);

                $scope.data=response; 

            }).error(function(response) {

             console.error("error in posting");

            });
        };
}])

我的html代码:

<html>
<head>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-controller="DataImportControl">
<form ng-submit="readCustomer()">

    <button type="submit" >Submit</button>
    </form>
<table class="table">
    <thead>
  <tr>
<th>Code exists in customer master</th>
  </tr>
    </thead>
<tbody>
<tr ng-repeat="cust in data ">
    <td>{{cust.customer_code}}</td>

</tr>
</tbody>
</table>

</div>
<div >
</div>

</body>

</html>

我的 json 数据作为控制器中的响应:

{"jarray":[{"customer_name":["Ankita"],"customer_code":["c501"]}]}

我的问题是如何在我的情况下使用 ng-repeat 在 html 中打印 json 数据?

提前谢谢...

【问题讨论】:

    标签: html angularjs json node.js


    【解决方案1】:

    从您的服务返回的数据格式奇怪。我假设您返回了多条记录,但在此示例中您只显示了一条。

    您在此处显示的记录是一个对象,具有一个数组作为属性之一。不清楚您的对象是否有多个数组,或者该数组是否嵌入了多个客户对象。但是,我设计了一个快速的 plunker,展示了如何在这两种情况下进行迭代。

    首先,如果您打算直接遍历data,并且data 将包含多个数组,您将使用(key, value) 语法,因为data 本身是一个对象而不是数组。

    <div ng-repeat="(key, value) in data">
      key: {{key}}
      <br/>value: {{value}}
      <div ng-repeat="customer in value">
        Customer name: {{customer.customer_name}}
        <br/>Customer code: {{customer.customer_code}}
      </div>
    </div>
    

    但是,如果您的数据仅返回单个对象属性 jarray,并且您将始终迭代同一属性,则外部 ng-repeat 是不必要的:

    <div ng-repeat="customer in data.jarray">
      Customer name: {{customer.customer_name}}
      <br/>Customer code: {{customer.customer_code}}
    </div>
    

    如果jarray 对数据没有特定意义,您可能需要清理服务,无论是在角度还是在您的服务器上。

    http://plnkr.co/edit/Nq5Bo18Pdj4yLQ13hnrJ?p=preview

    【讨论】:

      【解决方案2】:

      我假设您想打印出实际的对象,在这种情况下,只需执行

      {{客户| json}}

      将其包裹在前置标签中以对其进行美化。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-31
        • 1970-01-01
        • 2015-06-21
        • 2017-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-23
        相关资源
        最近更新 更多