【问题标题】:ng-table not showing data from http getng-table 未显示来自 http get 的数据
【发布时间】:2015-02-20 18:14:29
【问题描述】:

我正在尝试使用 angularjs 和 rails 制作一个带有 ajax 数据的 ng-table。 我看到 http get 已成功获取数据,但由于某种原因,我无法将其附加到我的表中,它总是不显示任何记录。 这是我的代码。 谢谢

(function(){
  var app = angular.module("apTags", ["ngTable"]);

  app.controller("apTagsController", function($scope, $timeout, $http, ngTableParams){
    $http.get('/owners/ap_tags/ap_tags_json.json')
    .success(function(data, status) {
      $scope.tags = data;

      $scope.tableParams = new ngTableParams({
          page: 1,            // show first page
          count: 10,           // count per page
          sorting: {name:'asc'}
      }, {
          total: $scope.tags.length, // length of data
          getData: function($defer, params) {
             var orderedData = $scope.tags;
            $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
            
          }
      });
    });
  });
})();
<div class="container" ng-app="apTags">
  <div ng-controller="apTagsController as list">
    <p><strong>Page:</strong> {{tableParams.page()}}</p>
    <p><strong>Count per page:</strong> {{tableParams.count()}}</p>
    <p>Filter: <input class="form-control" type="text" ng-model="filter.$" /></p>
    <table ng-table="tableParams" id="table_tags" class="table table-condensed table-bordered table-hover">
      <thead>
        <tr>
          <th>Tag</th>
          <th>Share</th>
          <th>Direct Product Count</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="tag in list.tags">
          <td >{{tag.name}}</td>
          <td >{{tag.share}}%</td>
          <td ></td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

还有我的 Rails 控制器

class Owners::ApTagsController < WlApplicationController
  respond_to :json, only: [:ap_tags_json]
  def index
    respond_to do |format|
      format.json do
        @tags = ApTag.all
        render :json => @tags.map(&:attributes)
      end
      format.html
    end
  end

  def ap_tags_json
    data = ApTag.all
    respond_with(data) do |format|
      format.json { render :json => data.map(&:attributes).as_json }
    end
  end
end

【问题讨论】:

    标签: javascript ruby-on-rails angularjs ngtable


    【解决方案1】:

    在您的 HTTP GET 请求的成功函数中,您将响应数据设置为$scope.tags

    然后在您的 HTML 中,当您对其进行迭代时,您将拥有 ng-repeat="tag in list.tags。将 tags 附加到 list 对象 ($scope.list = {}; $scope.list.tags = data;)。

    或者,在您的 HTML 中迭代正确的数据:ng-repeat="tag in tags"

    【讨论】:

    • 感谢您的回答,但它仍然对我不起作用。我定义了我的控制器
      这就是为什么在 ng-repeat 我称之为“list.tags 中的标签”
    【解决方案2】:

    使用 ng-table 时,您应该迭代 $data 而不是 list.tags。这个问题涵盖了更多细节:ng-table sorting not working

    【讨论】:

      猜你喜欢
      • 2017-03-25
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-15
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      相关资源
      最近更新 更多