1

I'm trying to make a ng-table with ajax data with angularjs and rails. I saw that the http get was successfully get the data but for some reason I coun't append it into my table, it always show no records. Here is my code. Thank you

(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>

and my rails controller

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
Louis
  • 103
  • 9

2 Answers2

0

In the success function of your HTTP GET request, you set the response data to $scope.tags.

Then in your HTML, when you iterate over it, you have ng-repeat="tag in list.tags. Either attach tags to the list object ($scope.list = {}; $scope.list.tags = data;).

Or, iterate over the right data in your HTML: ng-repeat="tag in tags".

  • Thanks for the answer but it still doesn't work for me. I defined my controller
    that's why in ng-repeat I called "tag in list.tags"
    – Louis Feb 20 '15 at 19:24
0

When using ng-table you should iterate over $data instead of list.tags. More details are covered by this question: ng-table sorting not working

Community
  • 1
  • 1
ristoh
  • 41
  • 3