Data retrieval issue with ng-table displaying information queried from HTTP request

I have been attempting to create an ng-table using ajax data with angularjs and rails. Despite successfully retrieving the data through an http get request, I am encountering difficulties appending it to my table as it always displays no records. Below is the code snippet in question. Any assistance would be greatly appreciated.

(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,
          count: 10,
          sorting: {name:'asc'}
      }, {
          total: $scope.tags.length,
          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>

Additionally, here is the relevant 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

Answer №1

After receiving the response from your HTTP GET request in the success function, you assign the data to $scope.tags.

Subsequently, in your HTML code, when looping through the data, you use ng-repeat="tag in list.tags". To make this work properly, you should either include tags within the list object like so:

$scope.list = {}; $scope.list.tags = data;
.

Alternatively, ensure you are iterating over the correct data in your HTML by using: ng-repeat="tag in tags".

Answer №2

It is recommended to utilize $data instead of list.tags when working with ng-table. For further information, refer to this query: ng-table sorting not functioning as expected

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

show small previews of pictures stored in a JavaScript array by using a for-loop

Currently stuck on a university project where I've set up an array of images like this: var testdata = [ { "imageID": 17, "uploadedDate": "2020-07-31 03:56:56.243139", "filepathOriginal": &qu ...

Identifying the Nearest Div Id to the Clicked Element

When a link is clicked, I am trying to locate the nearest div element that has an id. In this specific scenario, the target divs would be either #Inputs or #Stages. For example, if Page1 through 4 is clicked, I want to store the id #Inputs in a variable. ...

Creating Duplicates of a Component in React

I am looking for a way to render multiple instances of the same component. Let's take a look at the component that needs to be duplicated (this is just a placeholder example, not the actual component): import React from 'react'; function Du ...

Preserving the selected date in a textbox using jQuery DatePicker after a postback

How to Save DatePicker Date in a Textbox after a Postback $(function () { $("#Arrival").datepicker({ minDate: 0, dateFormat: 'dd/mm/yy', showOn: "button", buttonImage: "img/ui_cal_icon.gif", buttonIm ...

Tips for checking form input validity prior to opening a modelDialog

After successfully validating all required form fields, I am trying to open a modal dialog. Although I have managed to validate the form, I am struggling to write the code that will trigger the opening of the modal dialog upon successful validation. Do y ...

Guide to deploying a Rails app with Vue on the Heroku free plan

My project consists of a front-end built on Vue.js and a backend developed using Ruby on Rails. Now, I am looking to deploy it on Heroku's Free plan. Can someone provide me with the necessary reference documents or helpful links for guidance? Thank yo ...

What is the best method for submitting form data using AJAX?

I am currently facing an issue with submitting a form that I have created using HTML, JS, PHP, and AJAX. Despite my best efforts, the form does not submit as expected. I suspect that the problem lies within my insert function, but I cannot pinpoint exact ...

Can Angular be utilized within a web worker environment?

I am working on developing an SPA app using Angular and I am interested in sharing my Angular service called "WebService" with a web worker. The main goal is to have one centralized "WebService" that can be utilized by both the background (web worker) and ...

Is there a way to plot countries onto a ThreeJS Sphere?

Currently engaged in a project involving a 3D representation of Earth. Successfully created a 3D Sphere using ThreeJS ...

Is there a way to have two SVG files displayed on a single HTML page at the same time

Currently, I am facing an issue with my graphs. I have a line graph and a boxplot, but the boxplot is appearing below the line graph when I want it to be next to it. Any suggestions on how I can achieve this layout? Thank you! I attempted to use 2 differe ...

The TypeScript factory design pattern is throwing an error stating that the property does not

While working with TypeScript, I encountered an issue when trying to implement the factory pattern. Specifically, I am unable to access child functions that do not exist in the super class without encountering a compiler error. Here is the structure of my ...

Encountering a top-level-await issue while utilizing the NextJS API

Currently, I am in the process of creating an API using NextJS and MongoDB. To start off, I have set up some basic code at the beginning of the API file: const { db } = await connectToDatabase(); const scheduled = db.collection('scheduled'); Fol ...

What is the most effective method for identifying all deleted or inserted items in an original array using Javascript?

When the app is not changed, I have a list of numbers called originalArray. After making some modifications, I now have modifiedArray where some items were inserted or deleted from originalArray. I've written a function to identify all the items that ...

Sending data from an AngularJS app to Google App Engine using HTTP post

I'm facing a small issue where I am unable to successfully POST my data (comments) to the GAE datastore using angularjs. Can you please help me identify what's wrong with the following angularjs "post" or html code? ANGULAR: $scope.addComment = ...

What is the best way to hide an anchor tag with JavaScript?

I have spent countless hours searching through tutorials in an attempt to make the anchor tag disappear and reappear for my Login form, but none have seemed to work for me. Even after copying and pasting various solutions, nothing has worked. Below is the ...

How can I make one object's position target another grouped object in three.js, while still enabling rotation to track a camera in augmented reality?

Currently, I am utilizing a cutting-edge augmented reality library that specializes in advanced image tracking capabilities. Despite extensively studying this project, I have reached a point where I require assistance. Essentially, the library generates an ...

Place the `service` parameter into the `run` function

What are some examples of when to utilize the angular.run method? I have a service that is resource-intensive and takes a significant amount of time to initialize before it can be used in conjunction with my view. angular.module('myApp').service ...

Angular: What is the best way to populate a column in a table with individual dropdown menus in each cell, each containing unique values?

I am completely new to Angular and I am attempting to build a table to display user information. <div ng-controller="ContactController as cc" ng-app="MyApp" id="account-settings-page"> <div class="slds manage-account-table"> <table class="s ...

Fix a carousel layout problem

I've made changes to an HTML-PHP module to display portfolio images as a carousel, and I'm using the same module on this website too. However, I've encountered an issue with duplicate content and the previous-next navigation buttons. Can so ...

Discovering elements with Selenium

While using selenium, I stumbled upon this web element: <td style="padding-right: 10px; " **onclick="javascript:show_me('CarDetails.php?CarID=2358912&SubCatID=1**', '2358912', 560, 'ActiveLinkVisited');stat( '../& ...