Unable to bind Json Data with Table Header using AngularJS - angularjs

Im getting data in this format from api, but when i try binding it to table using angularjs it is creating empty space instead of values. Im also getting more then one table from some Api's please explain who to bind different datatables in different tables too. thanks
{"Table":
[{
"SchoolId":1,
"schoolname":"Microsoft",
"SCHOOLCODE":"29911583",
"WEBSITE":"JLR",
"USEREMAIL":"faucibus#aliquamiaculislacus.org",
"PHONE":"841-9331",
"ADDRESS1":"682-5760 Felis Street",
"ISACTIVE":0,
"PLANTYPE":3
}]
}
Angular Controller
SMSApp.factory('GetStudentService', function ($http) {
studobj = {};
studobj.getAll = function () {
var stud=[];
stud = $http({ method: 'Get', url: 'http://localhost:58545/api/Student?Studentid=1' }).
then(function (response) {
return response.data;
});
return stud;
};
return studobj;
});
SMSApp.controller('studentController', function ($scope, GetStudentService) {
$scope.msg = "Welcome from Controller";
GetStudentService.getAll().then(function (result) {
$scope.school = result;
console.log(result);
});
});
HTML Code
<tbody ng-controller="studentController">
<tr ng-repeat="schools in school track by $index">
<td>{{schools.SchoolId}}</td>
<td>{{schools.schoolname}}</td>
<td>{{schools.SCHOOLCODE}}</td>
<td>{{schools.WEBSITE}}</td>
<td>{{schools.USEREMAIL}}</td>
</tr>
</tbody>
WHAT I GET

Change in your Angular Controller :
SMSApp.controller('studentController', function ($scope, GetStudentService) {
$scope.msg = "Welcome from Controller";
GetStudentService.getAll().then(function (result) {
/********************* Changed Here ********************/
$scope.school = JSON.parse(result._body); // Or only JSON.parse(result)
$scope.school = $scope.school.table;
});
});
And your HTML Code :
<tbody ng-controller="studentController">
<tr ng-repeat="schools in school track by $index">
<td>{{schools.SchoolId}}</td>
<td>{{schools.schoolname}}</td>
<td>{{schools.SCHOOLCODE}}</td>
<td>{{schools.WEBSITE}}</td>
<td>{{schools.USEREMAIL}}</td>
</tr>
</tbody>

Naming the data school is confusing. Do instead:
GetStudentService.getAll().then(function (data) {
$scope.tableObj = data;
console.log(data);
});
<tbody ng-controller="studentController">
<tr ng-repeat="school in tableObj.Table track by school.SchoolId">
<td>{{school.SchoolId}}</td>
<td>{{school.schoolname}}</td>
<td>{{school.SCHOOLCODE}}</td>
<td>{{school.WEBSITE}}</td>
<td>{{school.USEREMAIL}}</td>
</tr>
</tbody>
From the Docs:
Best Practice: If you are working with objects that have a unique identifier property, you should track by this identifier instead of the object instance, e.g. item in items track by item.id. Should you reload your data later, ngRepeat will not have to rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones. For large collections, this significantly improves rendering performance.
— AngularJS ng-repeat API Reference

Just replace your result with result.Table in your controller because if you properly see your response it is inside "Table" named array. Try this you should be able to see your records
SMSApp.controller('studentController', function ($scope, GetStudentService) {
$scope.msg = "Welcome from Controller";
GetStudentService.getAll().then(function (result) {
$scope.school = result.Table;
console.log(result);
});
});
Note: I have replaced your API call in the jsfiddle link with the response mentioned in the question.
JSFiddle Link : http://jsfiddle.net/zu8q7go6/9/

Related

ng-repeat not displaying data when fetch via factory service

Need help to understand my mistake/ to display data on page.
I gone through almost every question on forum saying "ng-repeat not working". But still not able to find out the answer.
(Please note: First time I tried to fetch data by creating factory service with $http)
Please take a look at my below JavaScript code (Module, Controller and factory defined at one place)
//App declaration
var myApp = angular.module("appLeadsLogRpt", []);
//Controller declaration
myApp.controller('controllerLeadsLogRpt', ['dataService', fncontrollerLeadsLogRpt]);
function fncontrollerLeadsLogRpt(dataService) {
var vm = this;
//Table headers
vm.TableHeaders = ["Lead Id", "Source", "Create Date", "Status", "Contact Id", "Customer Name", "AssignedTo", "Mail Content", "Closed Reason", "Last Lead Note"];
dataService.getAllData()
.then(getData,null)
.catch(showError);
function getData(data) {
vm.LeadsLogRptData = JSON.parse(data);
//console.log(JSON.parse(data));
}
function showError(errMsg) {
console.log(errMsg);
}
}
//Factory Service to fetch data
myApp.factory('dataService', ['$http', DataService]);
function DataService($http) {
return {
getAllData: GetAllData
};
function GetAllData() {
return $http({
method: 'get',
url: 'DataHandler.ashx?method=leadsReport&listId=504473'
})
.then(sendResponseData)
.catch(sendError)
}
function sendResponseData(response) {
return response.data;
}
function sendError(response) {
return response.status;
}
}
</script>
And my Html like below:
<div id="DvContent" style="width:100%" data-ng-app="appLeadsLogRpt">
<div style="width:100%;" data-ng-controller="controllerLeadsLogRpt as vm1">
<input type="text" id="txtJsonData" value='<%=jsonLeadsLogRpt %>' style="display:none" />
<div><h3>Leads Log Report</h3></div>
<div style="text-align:right;margin-bottom:2px;padding-right:2px;">
<img src="/mp_images/excelicon.gif" border=0 width=22 height=22 alt="Open in Excel">
</div>
<div id="divExportToExcel">
<table style="width:100%" id="tblLeadLogRpt" class="table table-bordered">
<thead>
<tr style="background-color:#CCCCCC">
<th data-ng-repeat="item in vm1.TableHeaders" class="ng-cloack">{{item}}</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="item1 in vm1.LeadsLogRptData">
<td class="ng-cloack">{{item1.A_LeadId}}</td>
<td class="ng-cloack">{{item1.B_Source}}</td>
<td colspan="8"></td>
</tr>
<tr data-ng-if="LeadsLogRptData.length==0"><td colspan="10">Data Not Found</td></tr>
</tbody>
</table>
</div>
</div>
</div>
If I assign hard coded data return by server to ng-repeat it works fine
Please let me know what I am doing wrong.
One more question.
In factory I fetch data by calling get method of $http
If I want to call it by Post method, how do I pass params?
In Jquery, I doing it following way.
$.ajax({
url: 'AbcdHandler.ashx',
type: 'POST',
data: {
'method': 'ABCData',
'StartDate': startDate,
'EndDate': endDate
},
success: function (result) {
return JSON.parse(result);
},
error: OnError
});
Thanks in advance for reading and helping.
My latest observation:
when I write data on console, got this. (take a look on function getData(data))
[{"A_LeadId":"426429","B_Source":"LabX"},{"A_LeadId":"429369","B_Source":"LabX"},{"A_LeadId":"430586","B_Source":"Info"},{"A_LeadId":"430589","B_Source":"Info"},{"A_LeadId":"433848","B_Source":"LabX"},{"A_LeadId":"448592","B_Source":"Info"},{"A_LeadId":"451795","B_Source":"Bid"},{"A_LeadId":"453008","B_Source":"Low Bid"},{"A_LeadId":"453009","B_Source":"Low Bid"},{"A_LeadId":"453010","B_Source":"Low Bid"},{"A_LeadId":"455736","B_Source":"Info"},{"A_LeadId":"455743","B_Source":"Info"},{"A_LeadId":"457030","B_Source":"Info"},{"A_LeadId":"457052","B_Source":"LabX"},{"A_LeadId":"461503","B_Source":"Manually Entered"}]
If I copy this and directly assign to vm.LeadsLogRptData, system shows me output on screen properly.
e.g. vm.LeadsLogRptData = [{"A_LeadId":"426429","B_Source":"LabX"},......];
One more thing. When I check length of data, it shows me 621. ({{vm.LeadsLogRptData.length}})
Actually there are only 15 curly brackets pair ({}) and system should show me length as 15
Hope I explain/describe my issue correctly.
(Need something which converts my data properly in Json format)
Thanks,
I got answer
Just use eval with Json.parse and system start displaying data properly
e.g. vm.LeadsLogRptData = eval(JSON.parse(data));
Anyone please explain me the logic behind this?
Thanks to every one who read and replied so far.
Maybe you should use params property of $http object, like:
function GetAllData() {
return $http({
method: 'GET',
url: 'http://localhost:12345/DataHandler.ashx',
params: {method: "leadsReport", listId: 504473}
})
.then(sendResponseData)
.catch(sendError)
}
If you want to perform POST request, you should use it like this:
function PostData() {
return $http({
method: 'POST',
url: 'http://localhost:12345/DataHandler.ashx',
data: {exampleData: exampleData}
})
.then(sendResponseData)
.catch(sendError)
}
Remember to change http://localhost:12345/ for your server URL.

How to echo JSON array as Smart Table data with Angluarjs

I'm pretty new to Angular, and trying to build a table using Smart Table based on data I'm fetching from a REST api. I can build the table fine with manually entered data, but when I try to insert a JSON array of data from the server the resulting table is empty.
Currently I have the following set up:
dataFactory.js - calls the API and gets a JSON response:
app.factory('dataFactory', ['$http', function($http) {
var urlBase = 'http://myurl.com/api';
var dataFactory = {};
dataFactory.getOrders = function() {
return $http.get(urlBase + '/orders');
};
return dataFactory;
}]);
My view is fairly basic and looks like this using to the Smart Table extension:
<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>
And my MainController.js processes and stores the data, and builds the table:
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
];
}]);
What am I doing wrong? How can I get my data to show up in the table?
In the success callback you are updating $scope.orders and not $scope.orderTable. By the way use promise function then instead of success and error callback (extract from angularjs doc):
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

ASP.Net WEB API AND ANGULAR Not outputting one column vs another

I was able to set up a asp.net web api and scaffolding to my sql server database. The return of the records from sql server appears to be JSON. The model has a few tables linked to each other by foreign keys and only has 2 records right now. Comp_Id = 1 and 2. The results to my local api looks like this:
[{"ASSOC_INC_OFF":[{"OFFICERINVOLVEDs":[],"AIO_ID":1,"COMP_ID":1,"OFCNUM":1,"LINK_TYPE":null}],"CRITICALINCIDENTs":[{"CIType":"Physical Force resulting in Death or Serious Bodily Injury","CINotice":null,"CIMonitorRolledOut1":null,"CIDAMonitored":null,"CIOIMQuestions":null,"CICharged":null,"CIMonitor1":null,"CIMonitor2":null,"CINotes":null,"CIOfcCharges":null,"CIOutcome":null,"COMP_ID":1,"RolledOut_DT":null,"CI_ID":1,"CINotice_DT":"2016-01-07T00:00:00","CIOIMAllegNotes":null,"CIMonitorRolledOut2":null,"CIMonitorRolledOut3":null,"CIMonitorRolledOut4":null,"CIMonitorRolledOut5":null,"CIMonitorRolledOut6":null,"CIMonitorRolledOut7":null}],"COMP_ID":1,"FileNum":"case1","Received_DT":"2016-01-21T00:00:00","Completed_DT":null,"OIMIntake_DT":null,"Status":null,"Occurred_DT":null,"ComplaintType":null,"Source":"Chiefs Office","Precinct":"District 2","AddrCity":null,"AddrState":null,"AddrZip":null,"CaseSummary":null,"IABNotified_DT":null,"ClosureLetSent_DT":null,"CaseType":null,"OIMOutcome":null,"InitialFinding":null,"ClosedFindings":null,"OIMRecFinding":null,"timestamp":null,"Department":"DSD","Address":null,"DeclineReason":null,"Filenum2":null,"Filenum3":null,"OIMDiscRev_DT":null,"OIMInvRev_DT":null,"OIMInvRoute_DT":null,"OIMDiscRoute_DT":null,"CRORoute_DT":null},{"ASSOC_INC_OFF":[],"CRITICALINCIDENTs":[{"CIType":"Officer/Deputy-Involved Shooting","CINotice":null,"CIMonitorRolledOut1":null,"CIDAMonitored":null,"CIOIMQuestions":null,"CICharged":null,"CIMonitor1":null,"CIMonitor2":null,"CINotes":null,"CIOfcCharges":null,"CIOutcome":null,"COMP_ID":2,"RolledOut_DT":null,"CI_ID":2,"CINotice_DT":null,"CIOIMAllegNotes":null,"CIMonitorRolledOut2":null,"CIMonitorRolledOut3":null,"CIMonitorRolledOut4":null,"CIMonitorRolledOut5":null,"CIMonitorRolledOut6":null,"CIMonitorRolledOut7":null}],"COMP_ID":2,"FileNum":"cw1","Received_DT":"2016-01-03T00:00:00","Completed_DT":null,"OIMIntake_DT":null,"Status":"Active","Occurred_DT":null,"ComplaintType":null,"Source":"Citizen Walk-in","Precinct":"District 7","AddrCity":null,"AddrState":null,"AddrZip":null,"CaseSummary":null,"IABNotified_DT":null,"ClosureLetSent_DT":null,"CaseType":"District-Bureau","OIMOutcome":"Satisfactory","InitialFinding":"Formal","ClosedFindings":null,"OIMRecFinding":"Decline","timestamp":null,"Department":"DSD","Address":null,"DeclineReason":"Body Worn Camera","Filenum2":null,"Filenum3":null,"OIMDiscRev_DT":null,"OIMInvRev_DT":null,"OIMInvRoute_DT":null,"OIMDiscRoute_DT":null,"CRORoute_DT":null}]
I am able to bind COMP_ID to my view but when I add in CIType, nothings appears.
console.log($scope.complaints) returns:
My Controller looks like this:
app.controller('UpdateController', function ($scope, ComplaintService) {
getCities();
function getCities() {
ComplaintService.getCities()
.success(function (complaints) {
$scope.complaints = complaints;
})
.error(function (error) {
$scope.status = 'Unable to load customer data: ' + error.message;
});
}
});
My service looks like this:
app.factory('ComplaintService', ['$http', function ($http){
var urlBase = 'http://localhost:63942/api';
var ComplaintService = {};
ComplaintService.getCities = function () {
return $http.get(urlBase+ '/complaints');
};
return ComplaintService;
}]);
and my index looks like this:
<div class="row">
<div class="col-md-3" ng-controller="UpdateController">
<table class="table">
<tr>
<th>Id</th>
<th>CI TYPE</th>
<tr ng-repeat="a in complaints">
<td>{{a.COMP_ID}}</td>
<td>{{a.CIType }}</td>
</table>
</div>
I am certainly confused about why I can render out only COMPID but not the rest of this api contents as it is all listed under localhost:###/api/complaints.
var someResultArray = [];
$scope.complaints.forEach(function(elem){
//basically checks if this exists in the object to avoid undefined issues
if(elem.ASSOC_INF_OFF){
elem.ASSOC_INF_OFF.forEach(function(assoc){
//do something with each assoc, ex: push it to another array
someResultArray.push(assoc);
});
}
});
an object in javascript can be treated by dotting yourself down, or you can also address its content by index, even though its an object. So you could write elem["ASSOC_INF_OFF"], and it would still work.

Why can't I display data from Mongodb with Angular

and I am trying to display a collection called books in mongodb but for some reason I run into an ng-repeat dupes error. Also the data retrieved from my $http.get operation returns the HTML syntax of the entire page for some reason instead of accessing the data from the books collection. Thing is I created other programs prior to this where I had absolutely no problem with ng-repeat and they still work, the difference being the angular version is older. I am thinking that is the problem. If you have any insight on what I am doing wrong I would appreciate it. Thank you
Error:
Error: [ngRepeat:dupes]
http://errors.angularjs.org/1.3.14/ngRepeat/dupes?p0=book%20in%20library&p1=string%3A%3C&p2=%3C
Controller code:
var app = angular.module("myApp", []);
app.controller("bookCtrl", function($scope, $http) {
var refresh=function(){
$http.get('http://localhost:3000/storeHome').success(function(response){
console.log("I got the data I requested");
console.log(response); //returns HTML of the page instead of an object
$scope.library = response;
$scope.book="";
});
};
refresh();
});
Route code:
var express = require('express');
var router = express.Router();
var Book =require('../../models/book');
router.get('/', function(req, res) {
res.render('bookStore/storeHome');
});
//get all books from the database
router.get('/',function(req,res,next){
Book.find(function(err, books) {
if (err)
res.send(err);
console.log(books);
res.json(books);
});
});
Book model:
var mongoose = require('mongoose');
var BookSchema = new mongoose.Schema({
title: String,
author: String,
publisher: String,
year: Number
});
module.exports=mongoose.model('Book', BookSchema);
HTML
<div class="container" ng-app="myApp" ng-controller="bookCtrl">
<table class="table">
<!--omitted code in between -->
<tr ng-repeat="book in library"> <!-- I tried track by $index and it didn't work-->
<td>{{book.title}} </td>
</tr>
</div>
I think the nodejs response is wrong. The res.json...try another options please.
EDIT: LIke this: res.status(200).send({myBooksList:list})
or this: res.send(200,{myBooksList:list})
Im still not sure :D, sorry.
Change your template's ng-repeat to :
<tr ng-repeat="book in library track by $index">
It doesn't handle duplicate data very well as it tries to find an identifier that is unique for every item. But since there's duplicates in the data angular is unable to do so... We can use the assigned repeat index to track the item by.
This might work:
Book.find(function(err, books) {
if (err)
res.send(err);
res.end(JSON.stringify(books));
}
}));

Create filter based on date Angularjs

I am loading in this JSON into my angular app:
http://www.football-data.org/teams/354/fixtures/?callback=JSON_CALLBACK
I would like to only load fixtures that are up-coming i.e only show the fixture details that are later than the present time.
I have a controller as so:
.controller('fixturesController', function($scope, $routeParams, footballdataAPIservice) {
$scope.id = $routeParams.id;
$scope.fixtures = [];
$scope.pageClass = 'page-fixtures';
footballdataAPIservice.getFixtures($scope.id).success(function (response) {
$scope.fixtures = response;
});
});
HTML
<tr ng-repeat="fixture in fixtures.fixtures">
<td>{{$index + 1}}</td>
<td>{{teamName(fixture.awayTeam)}}</td>
Not sure how to do this, especially with the format I have for the time and day: "2015-03-14T15:00:00Z"
Your dates are already in the correct format for a date conversion, so you only need to create a filter yourself.
I'd just create a custom filter like the one I put down here. Adjust it to your needs.
angular.module('yourApp')
.filter('greaterThan', function() {
return function (actualDate, comparisonDate) {
return Date(actualDate) > Date(comparisonDate);
};
});
Then your HTML could look like this:
<tr ng-repeat="fixture in fixtures.fixtures | greaterThan:fixture.date:'2015-03-14T15:00:00Z'">
...
</tr>

Resources