Unable to bind json data to a table using angularjs - javascript

Hi i am Trying to Bind JSON object Data to a table.my issue is i am able to bind entire json object {{metric}} but failed to load each atttribute of json object i.e.,{{metric.EmpId}}.
finally from my observation i found when the converted json object is directly asigned to
$scope.Employees="Employee": [
{"EmpId": "4",
"Name": "Chris",
"Sex": "Male",
"Phone": [
{
"_Type": "Home",
"__text": "564-555-0122"
},
{
"_Type": "Work",
"__text": "442-555-0154"
}
],
"Address": {
"Street": "124 Kutbay",
"City": "Montara",
"State": "CA",
"Zip": "94037",
"Country": "USA"
}
}
]
}
the output is working as i expected but when i assign the direct result
i.e,$scope.Employees=response;it is not working what might be the issue
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="xml2json.js"></script>
<script>
var app = angular.module('httpApp', []);
app.controller('httpController', function ($scope, $http) {
$http.get("File1.xml",
{
transformResponse: function (cnv) {
var x2js = new X2JS();
var aftCnv = x2js.xml_str2json(cnv);
return aftCnv;
}
})
.success(function (response) {
console.log(response);
$scope.Employees = response;
console.log($scope.Employees);
});
});
</script>
<div>
<div ng-app="httpApp" ng-controller="httpController">
<div ng-repeat="metric in Employees">
{{ metric}}
<br />
<br />
<table>
<tr ng-repeat="metric in Employees">
{{metric}}
<td ng-repeat="cell in metric">{{cell}}</td>
<td>{{cell.EmpId}}</td>
<td>{{metric.Name}}</td>
</tr>
</table>
</div>
</div>

Assuming your json has the following format:
$scope.Employees = {
"Employee": [
{
"EmpId": 1,
"Name": "Sam"
},
{
"EmpId": 2,
"Name": "Lucy"
}
]
};
You probably would want to do this:
<div ng-repeat="employeeList in Employees">
<table>
<tr ng-repeat="employee in employeeList">
<td>{{employee.EmpId}}</td>
<td>{{employee.Name}}</td>
</tr>
</table>
</div>

Related

Add edit/delete icon to row of data populated by JSOn (AjaxCall)

I have an HTML table which is being populated by a JSON (ajax call). In the Edit and Delete columns of the table I need to have an icon to edit or delete the data on each row.
I don't know how to add the icon when the table is populated by the JSON.
Following is my code:
//JSON which is populating the table. Register.js
$(document).ready(function() {
var allRegister = AjaxCall(apiUrl, mthdGetReleasesFullList, null,
{
});
var data=allRegister.responseText;
alert("testing"+ data);
var jsonResponse = JSON.parse(data);
//var table = $('#contact-data').DataTable({
var table = $('#register-data').DataTable({
"data": jsonResponse.data,
"columns": [
{ "data": "ReleaseID" },
{ "data": "ReleaseName" },
{ "data": "DivisionID" },
{ "data": "StatusID" },
],
"order": [[1, 'dsc']]
});
});
Html code for table:
<link rel="stylesheet" href="entity/Register/css/Register.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Page specific JS -->
<script src="entity/Register/js/Register.js"></script>
<div class="container-full">
<div class="heading-1">
<input type="button" id="btn-AddUser" value="Add Release" style="font-size:14px;color:teal;text-align: left">
<h1>
</h1>
<div class="modular-box-text inset">
<div class="retgister-table-holder">
<h2>Pre-Release Access Register:</h2>
<br>
<div class="register-table" >
<table id="register-data"class="display tablesorter" role="grid" aria-describedby="example_info" style="width: 100%;" cellspacing="0">
<thead>
<tr>
<th>ReleaseID</th>
<th>ReleaseName</th>
<th>DivisionID</th>
<th>StatusIDth>
<th>Edit<th>
<th>Delete </th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
You need to work with the render option of the columns objects - documentation here. When you specify the targeted ID of your desired action (i presume it is ReleaseID) you just create more columns with that ID as data object and adjust the column renderer by giving it a custom render method. Since you specified ReleaseID as data, you can re-use that value in the render method as first argument.
In the example below you can see how to achieve this - You can very easily replace Edit and Delete text with <img /> tags referencing the icons you want to have for each action.
// Faking a request
var response = [
{ "ReleaseID": "1",
"ReleaseName": "Release A",
"DivisionID": "10",
"StatusID": "1"
}, {
"ReleaseID": "2",
"ReleaseName": "Release B",
"DivisionID": "9",
"StatusID": "2"
}, {
"ReleaseID": "3",
"ReleaseName": "Release C",
"DivisionID": "9",
"StatusID": "1"
}, {
"ReleaseID": "4",
"ReleaseName": "Release D",
"DivisionID": "10",
"StatusID": "2"
}, {
"ReleaseID": "5",
"ReleaseName": "Release E",
"DivisionID": "11",
"StatusID": "1"
}];
$(document).on('ready', function() {
$('#register-data').dataTable({
"data": response,
"columns": [
{ "data": "ReleaseID" },
{ "data": "ReleaseName" },
{ "data": "DivisionID" },
{ "data": "StatusID" },
{
"data": "ReleaseID",
"render": (data, type, row, meta) => `Edit`
}, {
"data": "ReleaseID",
"render": (data, type, row, meta) => `Delete`
}
],
"order": [[1, 'dsc']]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<table id="register-data"class="display tablesorter" role="grid" aria-describedby="example_info" style="width: 100%;" cellspacing="0">
<thead>
<tr>
<th>ReleaseID</th>
<th>ReleaseName</th>
<th>DivisionID</th>
<th>StatusID</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Thanks for your response.
I used the following to get Edit and Delete buttons to appear on all rows of table
var table = $('#register-data').DataTable({
"data": jsonResponse.data,
"columns": [
{ "data": "ReleaseID" },
{ "data": "ReleaseName" },
{ "data": "DivisionID" },
{ "data": "StatusID" },
{"data":null, "defaultContent": "<button class='btn-Edit'>Edit</button>"},
{"data":null, "defaultContent": "<button class='btn-Delete'>Click!</button>"},
],
"order": [[1, 'dsc']]
});

Import JSON to html (table) filtering results

I'm trying to import JSON data to a html table. I have different types of data. In my case I need only to see the "link" data type in a table this is the JSON data I'm getting.
{ "data": [
{
"type": "photo",
"created_time": "2017-11-15T14:30:43+0000",
"permalink_url": "https://www.facebook.com/LaFokaES/posts/693061044378702",
"shares": {
"count": 2270
},
"id": "104957429855736_693061044378702"
},
{
"type": "link",
"created_time": "2017-11-15T02:34:46+0000",
"permalink_url": "https://www.facebook.com/LaFokaES/posts/692656794419127",
"shares": {
"count": 86
},
"id": "104957429855736_692656794419127"
},
{
"type": "photo",
"created_time": "2017-11-15T00:34:50+0000",
"permalink_url": "https://www.facebook.com/LaFokaES/posts/692493157768824",
"shares": {
"count": 1628
},
"id": "104957429855736_692493157768824"
},
{
"type": "photo",
"created_time": "2017-11-14T23:51:53+0000",
"permalink_url": "https://www.facebook.com/LaFokaES/posts/692442954440511",
"shares": {
"count": 6239
},
"id": "104957429855736_692442954440511"
This is the code I have:
<body>
<input type="text" class="txtPagina">
<button class="btnBuscar">Buscar</button>
<table class="tabla" border='1'>
<tr>
<td>Type</td>
<td>created time</td>
<td>permalink url</td>
<td>Shares Count</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.btnBuscar').on('click', function (){
var pagina = $('.txtPagina').val();
//Ajax
$.ajax({
type: "GET",
dataType: "json",
url: "https://graph.facebook.com/"+pagina+"/feed?fields=type,created_time,permalink_url,shares&limit=25& access_token=(mytoken)",
success: function(data){
$.each(data.data, function(i, d){
var s = d.shares ? '<td>'+d.shares.count+'</td>' : '';
$('.tabla').append('<tr><td>'+d.type+'</td><td>'+d.created_time+'</td><td>'+d.permalink_url+'</td>'+s+'</tr>');
});
},
error: function (){
console.log("Error");
And this is the result I'm getting:
As you can see I'm getting photos and links but I need to see only links.
Just add an if statement in your loop to filter out the photos.
$.each(data.data, function(i, d){
if(d.type =='link'){
var s = d.shares ? '<td>'+d.shares.count+'</td>' : '';
$('.tabla').append('<tr><td>'+d.type+'</td><td>'+d.created_time+'</td><td>'+d.permalink_url+'</td>'+s+'</tr>');
}
});
in your each loop:
if(d.type == 'link') {
//Add as you already do
}
Done!

Angularjs ng-repeat with filter scope object

I have a requirement to filter rows in ng-repeat based on whats in $scope.filterObject. I have a data in $scope.customerData that contains all the customer information, but when looping through each customer, I would only like to show results based on whats in $scope.filterObject. For example, only show rows of customers that have jobs that are in $scope.filterObject.
Here is the JSFiddle link.
Here is what I have so far:
HTML:
<table ng-app="app" ng-controller="AppsCtrl">
<thead>
<tr>
<th>+</th>
<th>Name</th>
<th>Email</th>
<th>DOB</th>
<th>Hobby</th>
</tr>
</thead>
<tbody ng-repeat="customer in customerData">
<tr>
<td>+</td>
<td>{{customer.name}}</td>
<td>{{customer.email}}</td>
<td>{{customer.DOB}}</td>
<td>{{customer.Hobby}}</td>
</tr>
<tr class="showhide">
<td> </td>
<td>Degree</td>
<td>{{customer.Degree}}</td>
<td>Job title</td>
<td>{{customer.Job}}</td>
</tr>
<tr class="showhide">
<td></td>
<td>Country</td>
<td>{{customer.Country}}</td>
<td>City</td>
<td>{{customer.City}}</td>
</tr>
</tbody>
</table>
JS:
// AngularJS toggle table
var app = angular.module('app', []);
app.controller('AppsCtrl', function($scope) {
$scope.expandTable = function() {
console.log($(event.target).closest('tr').nextUntil("tr.main"));
$(event.target).closest('tr').nextUntil("tr.main").slideToggle();
// console.log($(event.currentTarget).parent().parent());
}
var data = [{
"name": "John",
"email": "JSmith#yahoo.com",
"DOB": "01/05/1968",
"Degree": " BSC",
"Job": "Engineer",
"Hobby": "Football",
"Country": "US",
"City": "Houston"
}, {
"name": "Jessica",
"email": "Jess#yahoo.com",
"DOB": "03/05/1976",
"Degree": " Accounting",
"Job": "CPA",
"Hobby": "Video games",
"Country": "US",
"City": "Fredericks"
}, {
"name": "Andrew",
"email": "AJoan#yahoo.com",
"DOB": "06/12/1998",
"Degree": " PHD",
"Job": "Professor",
"Hobby": "Writing",
"Country": "US",
"City": "San Diago"
}, {
"name": "Rich",
"email": "Rschol#yahoo.com",
"DOB": "09/21/1988",
"Degree": " PHD",
"Job": "Technician",
"Hobby": "Writing",
"Country": "US",
"City": "San Diago"
}];
$scope.customerData = data;
$scope.filterObject = [{
"Job": "CPA"
}, {
"Job": "Engineer"
}]
});
\
Any suggestion and help is really appreciated. :)
You can use angular filter function in ng-repeat to compare customerArray with customerObject and then return only element that match customerObject properties.
//Instead of array
$scope.filterObject = {
"Job": "CPA"
};
HTML :
<tr ng-repeat="customer in customerData | filter: filterObject">
Otherwise you can create a custom filter function to compare field or array of fields :
app.filter('customerFilter', function() {
return function( items, filterParams) {
var filtered = [];
angular.forEach(items, function(item) {
if(filterParams.Job.indexOf(item.Job) !== -1) {
filtered.push(item);
}
});
return filtered;
};
});
HTML :
<tr ng-repeat="customer in customerData | customerFilter: filters">
Customer controller:
$scope.filters = {
"Job" :["Technician","CPA"]
}
working example here : https://jsfiddle.net/Nedev_so/wb1hqeca/
$scope.customerData = data.filter(function(user){
var found = false;
$scope.filterObject.forEach(function(filter){
if(filter.Job === user.Job)
found = true;
})
return found;
});
Fiddle: https://jsfiddle.net/nandorpersanyi/yLsxqkx8/
Regarding Nedev's answer:
DOM filters can have an impact on performance, presuming we are handling large datasets (eg $scope.customerData has thousands of customers). In this case you are better off filtering within the controller, unless you need user interaction with the filter. And if your filter object updates dynamically, just $watch it for changes, then rerender customerData when changed

AngularJS rendering from deeply nested jsonp

I am new to JSON and also AngularJS. I'm trying to access data elements in a deeply nested remote json file. I can manage to render the whole JSON results in my view. However, I can't seem to target the elements that are in an array deep inside the JSON. It's from Yahoo Currency.
This is my controller and view that renders the entire JSON file:
controller
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$http.jsonp('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fwebservice%2Fv1%2Fsymbols%2Fallcurrencies%2Fquote%3Fformat%3Djson%22&format=jsonp&callback=JSON_CALLBACK').success(function (data) {
$scope.data = data;
});
});
view
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from JSON feed</h1>
<ul>
<li ng-repeat="row in data">
{{ data }}
</li>
</ul>
</body>
</html>
I tried writing the controller like this:
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$http.jsonp('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fwebservice%2Fv1%2Fsymbols%2Fallcurrencies%2Fquote%3Fformat%3Djson%22&format=jsonp&callback=JSON_CALLBACK').success(function (data) {
var pair = { name };
// $scope.data = data;
if(data) {
if (data.results) {
pair.name = data.results.list.resources[0].resource.fields.name;
}
}
});
});
But that doesn't work. Here is the JSON (partial) .. I'm trying to access the "name", "price", and "utctimestamp" fields for each resource:
{
"query": {
"count": 1,
"created": "2015-11-07T05:42:03Z",
"lang": "en-US",
"diagnostics": {
"publiclyCallable": "true",
"url": {
"execution-start-time": "0",
"execution-stop-time": "23",
"execution-time": "23",
"content": "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json"
},
"user-time": "25",
"service-time": "23",
"build-version": "0.2.311"
},
"results": {
"list": {
"meta": {
"type": "resource-list",
"start": "0",
"count": "173"
},
"resources": [
{
"resource": {
"classname": "Quote",
"fields": {
"name": "USD/KRW",
"price": "1152.994995",
"symbol": "KRW=X",
"ts": "1446874620",
"type": "currency",
"utctime": "2015-11-07T05:37:00+0000",
"volume": "0"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"name": "SILVER 1 OZ 999 NY",
"price": "0.068046",
"symbol": "XAG=X",
"ts": "1446850711",
"type": "currency",
"utctime": "2015-11-06T22:58:31+0000",
"volume": "100"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"name": "USD/VND",
"price": "22364.000000",
"symbol": "VND=X",
"ts": "1446874620",
"type": "currency",
"utctime": "2015-11-07T05:37:00+0000",
"volume": "0"
}
}
},
...
For what it's worth, jsonp seems to return some kind of xml-looking stuff when I append the callback=JSON_CALLBACK to the url, like this:
JSON_CALLBACK({"query":{"count":"1","created":"2015-11-07T16:08:29Z","lang":"en-US"},"results":["<list><meta><type>resource-list</type><start>0</start><count>173</count></meta><resources><resource><classname>Quote</classname><fields><name>USD/KRW</name><price>1152.994995</price><symbol>KRW=X</symbol><ts>1446900900</ts><type>currency</type><utctime>2015-11-07T12:55:00+0000</utctime><volume>0</volume></fields></resource></resources><resources><resource><classname>Quote</classname><fields><name>SILVER 1 OZ 999 NY</name><price>0.068046</price><symbol>XAG=X</symbol><ts>1446850711</ts><type>currency</type><utctime>2015-11-06T22:58:31+0000</utctime><volume>100</volume></fields></resource></resources><resources><resource>
...
Is there a problem with how I'm using JSONp? I'm getting the data set rendered to my view (above) but it's all in the funky xml syntax. How to go about grabbing the 3 values I need from that to an array and rendering in a <ul>??
You can use your original controller, you only had problems in the view. It would work if you substitute it by this one:
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from JSON feed</h1>
<ul>
<li ng-repeat="res in data.query.results.list.resources">
{{ res.resource.fields.name }}: {{ res.resource.fields.price }}, {{ res.resource.fields.utctime }}
</li>
</ul>
</body>
</html>
Here is the Plunker using your JSON example: http://plnkr.co/edit/wzF5t9dTZt49n5eq9N1L?p=preview

ng-repeat with key and value then use the key to be a directive value for ng-model

It is possible to have the key for a scope variable to be used in a ng-model directive?
What I wanted is not to manually put the keys for each ng-model directive, I just wanted to use the ng-repeat and get the key for a scope variable and put it on the ng-model inside the ng-repeat directive.
I'm just a newbie on this framework. Any help would be greatly appreciated
Markup snippet
<div ng-show="editing">
<input ng-repeat="(key, value) in editing" ng-model="editing.key">
</div>
HTML
<html ng-app>
<head>
<title>Demo</title>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/controllers/app.js"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-responsive.min.css">
</head>
<body>
<div classs="container" ng-controller="UserProfile">
<ul>
<li ng-repeat="user in users">{{user.id}} - {{user.fname}} </li>
</ul>
<div ng-show="editing">
<input ng-repeat="(key, value) in editing" ng-model="editing.key">
</div>
</div>
</body>
</html>
Javascript
function UserProfile ($scope) {
$scope.users = {
"ID01": {
"id": "ID01",
"fname": "Vincent",
"lname": "Panugaling",
"gender": "male",
"age": "21",
},
"ID02": {
"id": "ID02",
"fname": "Adrian",
"lname": "Santos",
"gender": "male",
"age": "22"
},
"ID03": {
"id": "ID03",
"fname": "Incognito",
"lname": "Mode",
"gender": "female",
"age": "21"
}
};
$scope.editProfile = function (id) {
$scope.editing = $scope.users[id];
};
}
Is this view you are expecting please have a look, yes it is possible to use key as ng-model.
Hey dude you are using angular 1.0.1 version thats why you can edit once and focus is getting out use latest version check out the same demo
updated fiddle
html code
<div classs="container" ng-app="app" ng-controller="UserProfile">
<ul>
<li ng-repeat="user in users">{{user.id}} - {{user.fname}} </li>
</ul>
<div ng-show="editing">
<input ng-repeat="(key, value) in editing" ng-model="editing[key]">
</div>
</div>
angular.js
var app = angular.module('app', []);
function UserProfile ($scope) {
$scope.users = {
"ID01": {
"id": "ID01",
"fname": "Vincent",
"lname": "Panugaling",
"gender": "male",
"age": "21",
},
"ID02": {
"id": "ID02",
"fname": "Adrian",
"lname": "Santos",
"gender": "male",
"age": "22"
},
"ID03": {
"id": "ID03",
"fname": "Incognito",
"lname": "Mode",
"gender": "female",
"age": "21"
}
};
$scope.editProfile = function (id) {
$scope.editing = $scope.users[id];
};
}

Categories