Angularjs : ngRepeat list down all the data from server - javascript

I successfully fetch data by using $http get from php server. But I have no idea how to display the data in Table form by using ngRepear because all the data is in few different project. I am going to display all the object of data into different row of a table. The following shows data I got from php server.

Following glimpse of code can give you idea
$scope.retrievedData = [];
//retrieve data from your server
//take the data into above scope variable
<table>
<tr ng-repeat = "data in retrievedData">
<td>data.AssetDescription</td>
<td>data.AssetNumber</td>
<td>data.ComputerName</td>
</tr>
</table>

You need to add that data to controller variable:
Controller
function YourController($scope, $http) {
$scope.tableData = [];
$http.get('url').then(function(result) {
$scope.tableData = result.data;
});
}
Template
<table>
<thead>
<tr>
<th>Description</th>
<th>Computer name</th>
<th>Borrow date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in tableData ">
<td>{{row.data.AssetDescription}}</td>
<td>{{row.data.ComputerName}}</td>
<td>{{row.data.borrowDate}}</td>
</tr>
</tbody>
</table>

Related

Sorting data from API to table using jQuery

I trying to learn jquery as im new to it. here I have made a request to this example API and got an array of object that i have to list in to the table. However, im stuck on how to sort in to the table? please help me out
I have my html
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td data-column="ID" id="_id"></td>
<td data-column="Name" id="_name"></td>
<td data-column="Age" id="_age"></td>
<td data-column="Salay" id="_salay"></td>
</tr>
</tbody>
</table>
and my script
$(document).ready(function(){
$("button").click(function(){
$.get("http://dummy.restapiexample.com/api/v1/employees", function(data, status){
if(data.status == "success"){
let listData = JSON.parse(data.data)
console.log(listData);
}
});
});
});
here i got an error as below:
Uncaught SyntaxError: Unexpected token o in JSON at position 1
at Function.parse [as parseJSON] ()
$.each(listData,function(key,value){
var trrow='<tr><td data-column="ID" id="_id">'+value["ID"]+'</td><td data-column="Name" id="_name">'+value["Name"]+'</td><td data-column="Age" id="_age">'+value["Age"]+'</td><td data-column="Salay" id="_salay">'+value["Salay"]+'</td>
</tr>';
$("tbody").append(trrow);
});
Basically you are again parsing a JSON array which is return from API.
Your API is returning the below data.
var data={"status":"success","data":[{"id":"1","employee_name":"Tiger Nixon","employee_salary":"320800","employee_age":"61","profile_image":""},{"id":"2","employee_name":"Garrett Winters","employee_salary":"170750","employee_age":"63","profile_image":""},{"id":"3","employee_name":"Ashton Cox","employee_salary":"86000","employee_age":"66","profile_image":""},{"id":"4","employee_name":"Cedric Kelly","employee_salary":"433060","employee_age":"22","profile_image":""},{"id":"5","employee_name":"Airi Satou","employee_salary":"162700","employee_age":"33","profile_image":""},{"id":"6","employee_name":"Brielle Williamson","employee_salary":"372000","employee_age":"61","profile_image":""},{"id":"7","employee_name":"Herrod Chandler","employee_salary":"137500","employee_age":"59","profile_image":""},{"id":"8","employee_name":"Rhona Davidson","employee_salary":"327900","employee_age":"55","profile_image":""},{"id":"9","employee_name":"Colleen Hurst","employee_salary":"205500","employee_age":"39","profile_image":""},{"id":"10","employee_name":"Sonya Frost","employee_salary":"103600","employee_age":"23","profile_image":""},{"id":"11","employee_name":"Jena Gaines","employee_salary":"90560","employee_age":"30","profile_image":""},{"id":"12","employee_name":"Quinn Flynn","employee_salary":"342000","employee_age":"22","profile_image":""},{"id":"13","employee_name":"Charde Marshall","employee_salary":"470600","employee_age":"36","profile_image":""},{"id":"14","employee_name":"Haley Kennedy","employee_salary":"313500","employee_age":"43","profile_image":""},{"id":"15","employee_name":"Tatyana Fitzpatrick","employee_salary":"385750","employee_age":"19","profile_image":""},{"id":"16","employee_name":"Michael Silva","employee_salary":"198500","employee_age":"66","profile_image":""},{"id":"17","employee_name":"Paul Byrd","employee_salary":"725000","employee_age":"64","profile_image":""},{"id":"18","employee_name":"Gloria Little","employee_salary":"237500","employee_age":"59","profile_image":""},{"id":"19","employee_name":"Bradley Greer","employee_salary":"132000","employee_age":"41","profile_image":""},{"id":"20","employee_name":"Dai Rios","employee_salary":"217500","employee_age":"35","profile_image":""},{"id":"21","employee_name":"Jenette Caldwell","employee_salary":"345000","employee_age":"30","profile_image":""},{"id":"22","employee_name":"Yuri Berry","employee_salary":"675000","employee_age":"40","profile_image":""},{"id":"23","employee_name":"Caesar Vance","employee_salary":"106450","employee_age":"21","profile_image":""},{"id":"24","employee_name":"Doris Wilder","employee_salary":"85600","employee_age":"23","profile_image":""}]};
let listData = JSON.parse(data.data) // replace this line
let listData=data.data;// its already JSON Array
for Example
var a=[{name:"John"},{name:"DOE"}]
JSON.parse(a) // it will give you same error which is mentioned in a question.

Angular Datatables REST based per page data with explicit table rendering

I have followed the approach "DataTables: Custom Response Handling" by Fabrício Matté. However, my requirement is to avoid rendering of table's rows and columns via callback. Instead, would like to traverse the current ajax request returned json data and render explicit html (tr/td) to have more control. Due to this, currently i see data shown twice on my table. At the same time, i understand that callback is rendering the page related buttons: prev, 1,2 next etc and click events which i would like to reuse and wan't to avoid custom implementation.
JS:
function notificationsCtrl($scope,$http,$resource, DTOptionsBuilder, DTColumnBuilder) {
var vm = this;
vm.notifications = [];
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withOption('serverSide', true)
.withOption('ajax', function(data, callback, settings) {
// make an ajax request using data.start and data.length
$http.get('notifications/list?page=' + (((data.start)/10)+1)).success(function(res) {
// map your server's response to the DataTables format and pass it to
// DataTables' callback
callback({
recordsTotal: 120,
recordsFiltered: 120,
data: res
});
vm.notifications = res;
});
})
.withDataProp('data') // IMPORTANT¹
.withOption('processing', true)
.withPaginationType('full_numbers');
$scope.dtColumns = [
DTColumnBuilder.newColumn('notificationId').withTitle('notificationId'),
DTColumnBuilder.newColumn('createUserId').withTitle('createUserId'),
DTColumnBuilder.newColumn('Language').withTitle('language')
];
}
HTML: sample but actual will require extra processing for some of the td tags
<table datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Language</th>
<th>Last Updated</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="notification in wynkCMSToolApp.notifications">
<td>{{ notification.notificationId }}</td>
<td>{{ notification.title }}</td>
<td>{{ notification.Language }}</td>
</tr>
</tbody>
</table>
If you want to render directly in the HTML, consider using the Angular renderer. However, such renderer does not support the server side processing.
So I recommend you use the server side processing along with the columns.render function.
Here an example of using the render function.

Knockout.js: Updating objects loaded with mapping plugin

I want to render a table containing a list of objects my server is sending me. I'm currently doing this:
<table>
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody data-bind="foreach: services">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: name"></td>
<td data-bind="text: status"></td>
</tr>
</tbody>
</table>
And the Knockout.js binding part:
var mappedData = komapping.fromJSON('{{{ services }}}');
ko.applyBindings({services: mappedData});
services is a variable containing JSON data and the whole page is rendered with handlebars. So far so good. I'm able to render the data received in the table.
Now the problem: I'd like to receive a notification which tells me that the status of a service has changed, and update the corresponding object within mappedData. The problem is that mappedData seems pretty opaque and I'm unable to retrieve an object and update it given its id.
Help appreciated!
Your mappedData variable at this point will be a knockout array with a bunch of objects that contain knockout observables.
So all you have to do is change the status observable in the correct object from the array.
function updateServiceStatus(id, status) {
var service = mappedData().filter(function(e) { return e.id() == id; });
if (service.length) {
service[0].status(status);
}
}
To get the object, you can write a helper function that will retrieve for you a service object. You could do something like this (assuming mappedData is an observableArray and id observable) :
function get_service_by_id(service_id){
for(var i=0;i<mappedData().length;i++){
if (mappedData()[i].id() === service_id){
return mappedData()[i];
}
}
return false;
}

Obtain data from Json using angular

Below is my code:
post.json
[
{
"client_id":"100",
"client_name":"MM Hope House",
"user_fname":"Betty",
"user_lname":"Johnson",
"user_id":"10",
"username":"bjohnson",
"total_web":"$500",
"campaigns":{
"campaign":[{
"id":"23",
"campaign_name":"MM Hope House",
"start_date":"4/15/2015",
"end_date":"6/13/2015",
"goal":"$20,000",
"total_pledges":"$1550",
"total_donations":"$1000"
}],
"pledgees":[{
"pledgee_fname":"Tavonia",
"pledgee_lname":"Evans",
"pledge_email":"tavonia#gmail.com",
"pledge_date":"4/22/2015",
"pledge_amount":"$50.00",
"paid":"$50.00",
"last_pledge":"$50.00"
}],
"donors":[{
"donor_fname":"Pat",
"donor_lname":"Smith",
"donor_email":"patsmith#onlinemediainteractive.com",
"total_cdonation":"$10.00",
"total_ldonation":"$450.00",
"last_donation":"$200.00",
"last_pledge":"$350.00"
}]
}
}
]
My HTML code:
<script>
function PostsCtrlAjax($scope, $http) {
$http({method: 'POST', url: 'assets/js/posts.json'})
.success(function(data) {
console.log(data);
$scope.posts = data;
})
.error(function(data, status) {
$scope.posts = data || "Request failed";
});
}
</script>
My HTML code where I want to populate data:
<thead>
<tr>
<th>Campaign ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Amount</th>
<th>Email ID.</th>
<th>Pledge Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="post in posts" >
<td>{{post.id}}</td>
<td>{{post.pledgee_fname}}</td>
<td>{{post.pledgee_lname}}</td>
<td>{{post.pledge_amount}}</td>
<td>{{post.pledge_email}}</td>
<td>{{post.pledge_date}}</td>
I am trying to get client_id pleg_fname from array, but do not know how to.
Your pledgess object is an array of objects so you should do this instead and your entire JSON is contained within an array so you need the first element which will be your entire object and you call it with posts[0] and then you specify the object you are trying to iterate : pledgees.
<tr ng-repeat="post in posts[0].campaigns.pledgees" >
<td>{{posts[0].campaigns.campaign[0].id}}</td>
<td>{{post.pledgee_fname}}</td>
<td>{{post.pledgee_lname}}</td>
<td>{{post.pledge_amount}}</td>
<td>{{post.pledge_email}}</td>
<td>{{post.pledge_date}}</td>
Edit
You're right, I totally missed that array. See this plunker where I tested it http://plnkr.co/edit/dvdnjv2mN2gljQGI9Lls?p=preview
Edit 2
If you want the campaign ID just add this (updated the original code with this change)
{{posts[0].campaigns.campaign[0].id}}
Because of your posts object contains an array of one element, you should use posts[0] to get the first (and the only one) element. Moreover, your pledgees array is inside a campaigns object, so posts[0] become posts[0].compaigns.pledgees.
You should try this :
<tr ng-repeat="post in posts[0].campaigns.pledgees" >
<td>{{post.id}}</td>
<td>{{post.pledgee_fname}}</td>
<td>{{post.pledgee_lname}}</td>
<td>{{post.pledge_amount}}</td>
<td>{{post.pledge_email}}</td>
<td>{{post.pledge_date}}</td>
</tr>
EDIT:
And, if you want the id from the campagin object at the same index than your pledgee item, you have to add track by $index to posts[0].campaigns.pledgees. So it's become posts[0].campaigns.pledgees track by $index.
So, now with $index you get the right index to get the right campaign ID in the campaign object with {{posts[0].campaigns.campaign[$index].id}}
And the result is :
<tr ng-repeat="post in posts[0].campaigns.pledgees track by $index" >
<td>{{posts[0].campaigns.campaign[$index].id}}</td>
<td>{{post.pledgee_fname}}</td>
<td>{{post.pledgee_lname}}</td>
<td>{{post.pledge_amount}}</td>
<td>{{post.pledge_email}}</td>
<td>{{post.pledge_date}}</td>
</tr>
You can see the result here : http://jsfiddle.net/Fieldset/y1asxm61/1/

How to get information from datatable - javascript - MVC

I have created an ASP.net MVC app and I have created a DataTable [DataTable.net] as follows:
<table id="invoiceTable">
<thead>
<tr>
<th>Invoice ID</th>
<th>Date</th>
<th>Reciept Date</th>
<th>Category</th>
<th>Total Value</th>
<th>Invoice Ref</th>
<th>Client</th>
<th>Status</th>
</tr>
</thead>
<tbody>
#{
foreach (FreeAgentApp.Models.CustomInvoice _invoice in ViewBag.Invoices)
{
<tr>
<td>#_invoice.InvoiceId</td>
<td>#_invoice.Date</td>
<td>#_invoice.RecpDate</td>
<td>#_invoice.Category</td>
<td>#_invoice.TotalValue</td>
<td>#_invoice.InvoiceRef</td>
<td>#_invoice.Client</td>
<td>#_invoice.Status</td>
</tr>
}
}
</tbody>
</table>
And i can get the information from a row when its selected using javascript as follows:
// Row data
$(document).ready(function () {
oTable = $('#invoiceTable').dataTable();
oTable.$('tr').click(function () {
var data = oTable.fnGetData(this);
alert(data);
// ... do something with the array / object of data for the row
});
});
The variable data will provide a string of every value in the row separated by a comma as follows:
"000,26-01-14,27-01-14,001,1000,inv,something ltd,paid"
I want to have all these values separated. Note this could be done by splitting on the comma however a value in the table could contain commas.
How can I separate this string?
According to the DataTables documentation oTable.fnGetData(this); return an array filled with the data of the definitions in the row so you should be able to acces the data directly from data.
var invoiceId = data[0];
var date = data[1];
var recpDate = data[2];
// etc. etc.

Categories

Resources