如何使用Angluarjs将JSON数组作为智能表数据进行回显

时间:2016-01-28 14:13:00

标签: arrays angularjs json smart-table

我对Angular很陌生,并尝试使用基于从REST api获取的数据的智能表构建表。我可以使用手动输入的数据构建表格,但是当我尝试从服务器插入JSON数据数组时,结果表为空。

目前我有以下设置: dataFactory.js - 调用API并获取JSON响应:

app.factory('dataFactory', ['$http', function($http) {

  var urlBase = 'http://myurl.com/api';
  var dataFactory = {};

  dataFactory.getOrders = function() {
    return $http.get(urlBase + '/orders');
  };

  return dataFactory;
}]);

我的观点相当基本,看起来像是使用Smart Table扩展程序:

<div ng-controller="MainController">
    <table st-table="ordersTable" class="table table-striped">
        <thead>
        <tr>
            <th st-sort="createdBy">Name</th>
            <th st-sort="id">ID</th>
            <th st-sort="state">State</th>
        </tr>
        </thead>
        <tbody>
        <tr ng-repeat="row in ordersTable">
            <td>{{row.createdBy}}</td>
            <td>{{row.id}}</td>
            <td>{{row.state}}</td>
        </tr>
        </tbody>
    </table>
</div>

我的MainController.js处理并存储数据,并构建表:

app.controller('MainController', ['$scope', 'dataFactory', function($scope, dataFactory) {
  $scope.status;
  $scope.orders;
  getOrders();

  function getOrders() {
    dataFactory.getOrders()
      .success(function(ord) {
        $scope.orders = ord;
      })
      .error(function(error) {
        $scope.status = 'Unable to load order data: ' + error.message;
      });
  }

  $scope.ordersTable = [
    // If I build the data manually the table builds using the following 3 lines
    //{createdBy: 'Laurent', id: '56433', state: 'Open')},
    //{createdBy: 'Blandine', id: '34367', state: 'Open')},
    //{createdBy: 'Francoise', id: '34566', state: 'Closed'}
    //... however I actually want the data to come from the JSON array returned by my factory like this:

    $scope.orders
  ];
}]);

我做错了什么?如何让我的数据显示在表格中?

1 个答案:

答案 0 :(得分:1)

在成功回调中,您正在更新$ scope.orders而不是$ scope.orderTable。顺便说一句,使用promise函数代替成功和错误回调(从angularjs doc中提取):

  

$ http遗留承诺方法成功与错误已被弃用。请改用标准方法。如果$ httpProvider.useLegacyPromiseExtensions设置为false,则这些方法将抛出$ http / legacy错误。