how to repeat the rows for the key of key value - html

I received the json data in AngularJs and want to display the particular value of json data in table using ng-repeat.
json data:
{
"15":{
"Unique number":"133077",
"Designation":"Software Engineer",
},
"16":{
"Unique number":"133079",
"Designation":"Senior Software Engineer",
},
"18":{
"Unique number":"143688",
"Designation":"Senior Software Engineer",
}
}
I want to display in table like this using HTML:
| uniq no | designation |
| 133077 | Software Engineer |
| 133079 | Senior Software Engineer |
| 143688 | Senior Software Engineer |
Any help please.
Thanks in advance.

angular.module('app',[]).controller('myCtrl', function($scope){
$scope.members = {
"15":{
"Unique number":"133077",
"Designation":"Software Engineer",
},
"16":{
"Unique number":"133079",
"Designation":"Senior Software Engineer",
},
"18":{
"Unique number":"143688",
"Designation":"Senior Software Engineer",
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<table>
<thead>
<th>SI.NO</th>
<th>Unique number</th>
<th>Designation</th>
</thead>
<tbody>
<tr ng-repeat="member in members">
<td>{{$index + 1}}</td>
<td>{{member['Unique number']}}</td>
<td>{{member.Designation}}</td>
</tr>
</tbody>
</table>
</div>

EDIT : OP changed the requirement to add an extra field to display serial number.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.data = {"15":{
"Unique number":"133077", "Designation":"Software Engineer", },
"16":{
"Unique number":"133079", "Designation":"Senior Software Engineer", },
"18":{
"Unique number":"143688", "Designation":"Senior Software Engineer", }
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div ng-app="myApp" ng-controller="myCtrl">
<table class="table table-bordered table-striped">
<thead>
<th>Sl. No.</th>
<th>Unique number</th>
<th>Designation</th>
</thead>
<tr ng-repeat='(key, value) in data'>
<td>
{{$index + 1}}
</td>
<td>
{{value["Unique number"]}}
</td>
<td>
{{value["Designation"]}}
</td>
</tr>
</table>
</div>

My solution base on new components architecture simple for understand:
(function() {
'use strict';
// app.js
angular
.module('app', [])
.component('myApp', {
template: '<items-table items="$ctrl.items"></items-table>',
bindings: {},
controller: function() {
this.items = {
"15": {
"Designation": "Software Engineer",
"Unique number": "133077"
},
"16": {
"Designation": "Senior Software Engineer",
"Unique number": "133079"
},
"18": {
"Designation": "Senior Software Engineer",
"Unique number": "143688"
}
};
}
});
const itemsTableTemplate = `
<div class="items">
<h2>Items</h2>
<table>
<thead>
<tr>
<th>unique no</th>
<th>designation</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(id, item) in $ctrl.items track by id">
<td ng-bind="item['Unique number']"></td>
<td ng-bind="item['Designation']"></td>
</tr>
</tbody>
</table>
</div>
`;
// items-table.component.js
angular
.module('app')
.component('itemsTable', {
template: itemsTableTemplate,
bindings: {
items: '<'
},
controller: ItemsTableController,
controllerAs: '$ctrl'
});
function ItemsTableController() {
// Constructor
}
angular.bootstrap(document.getElementById('app'), ['app'], {
strictDi: true
})
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div id="app">
<my-app>
Loading...
</my-app>
</div>

Related

AngularJs read json file not recognized

I am testing AngularJS. I am trying to read a json file with http.get and show it in a ng-repeat.
I have two problems...
First, the file with .json extension is not recognized. I have to rename it with .js extension
Second, the format elements in the file are not recognize. Repeater is filled with empty rows.
Here is my Angular.html
<!DOCTYPE html>
<html ng-app="exampleApp">
<head>
<title>Ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="angular.js"></script>
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap-theme.css" rel="stylesheet" />
<script>
angular.module("exampleApp", [])
.controller("defaultCtrl", function ($scope, $http) {
$scope.loadData = function () {
$http.get("productData.js").success(function (data) {
$scope.products = data;
});
}
});
</script>
</head>
<body ng-controller="defaultCtrl">
<div class="panel panel-default">
<div class="panel-body">
<table class="table table-striped table-bordered">
<thead><tr><th>Name</th><th>Category</th><th>Price</th></tr></thead>
<tbody>
<tr ng-hide="products.length">
<td colspan="3" class="text-center">No Data</td>
</tr>
<tr ng-repeat="item in products">
<td>{{name}}</td>
<td>{{category}}</td>
<td>{{price | currency}}</td>
</tr>
</tbody>
</table>
<p>
<button class="btn btn-primary" ng-click="loadData()">
Load Data
</button>
</p>
</div>
</div>
</body>
</html>
Here is my ProductData.js
[{ "name": "Apples", "category": "Fruit", "price": 1.20, "expiry": 10 },
{ "name": "Bananas", "category": "Fruit", "price": 2.42, "expiry": 7 },
{ "name": "Pears", "category": "Fruit", "price": 2.02, "expiry": 6 },
{ "name": "Tuna", "category": "Fish", "price": 20.45, "expiry": 3 },
{ "name": "Salmon", "category": "Fish", "price": 17.93, "expiry": 2 },
{ "name": "Trout", "category": "Fish", "price": 12.93, "expiry": 4 }]
What I am doing wrong?
Thanks.
Rename your file as productdata.json. and change your code according to it
angular.module("exampleApp", [])
.controller("defaultCtrl", function ($scope, $http) {
$scope.loadData = function () {
$http.get("productData.json").success(function (data) {
$scope.products = data;
});
}
});
Also if you are using angularjs version above 1.3 replace .Success with .Then, because .Success has been deprecated
I have found why it does not appear... It was my mistake.. I had to replace
<tr ng-repeat="item in products">
<td>{{name}}</td>
<td>{{category}}</td>
<td>{{price | currency}}</td>
</tr>
for this one
<tr ng-repeat="item in products">
<td>{{item.name}}</td>
<td>{{item.category}}</td>
<td>{{item.price | currency}}</td>
</tr>
I have forgotten to add item.
Anyway.. I could not find why my PC do not accept .json file... If I put those file in IIS directory and run it from IIS, it Works fine.. But it does not work from outside IIS.

iterating through nested collections to create table with Angular ng-repeat

I'm learning Angular and came across some difficulty when creating table from nested collection.
I simplified a bit my data and table for this example. Please help ;)
Here is what I want to achieve (note continent and country can span across multiple columns):
Continent: | Europe | Asia |
Country: | UK | Spain | China |
City: | Edinburgh | London | Barcelona | Beijing |
Population:| 500000 | 9000000 | 15000000 | 22000000 |
Here is data structure:
function playerCtrl($scope) {
$scope.continents = [
{
"continent": "Europe",
"columnSpan": 3,
"countries": [
{
"country": "UK",
"columnSpan": 2,
"cities": [
{
"city": "Edinburgh",
"info": [
{"population": 500000}
]
},
{
"city": "London",
"info": [
{"population": 9000000}
]
}
]
},
{
"country": "Spain",
"columnSpan": 1,
"cities": [
{
"city": "Barcelona",
"info": [
{"population": 15000000}
]
}
]
}
]
},
{
"continent": "Asia",
"columnSpan": 1,
"countries": [
{
"country": "China",
"columnSpan": 1,
"cities": [
{
"city": "Beijing",
"info": [
{"population": 22000000}
]
}
]
}
]
}
];
}
Here is what I have so far for HTML (continents row is easy, struggling with rest):
<div ng-app>
<div class="container-fluid">
<div class="row">
<!-- Player section -->
<div class="col-sm-8" ng-controller="playerCtrl">
<table class="table table-bordered">
<tr>
<th>Continent:</th>
<td ng-repeat="continent in continents" colspan="{{continent.columnSpan}}">{{continent.continent}}</td>
</tr>
<tr>
<th>Country:</th>
<td ng-repeat="country in continents.countries" colspan="{{country.columnSpan}}">{{country.country}}</td>
</tr>
<tr>
<th>City:</th>
<td ng-repeat="city in country.cieties in continents.countries">{{city.city}}</td>
</tr>
<tr>
<th>Population:</th>
<td ng-repeat="city in country.cieties in continents.countries">{{city.info.population}}</td>
</tr>
</table>
</div>
Link to jsfiddle : https://jsfiddle.net/7on62750/
With a little help of a friend I managed to solve this!
solution was to create functions that get me sub-collections.
Feels a bit hacky so feel free to post better solutions.
JS:
function GetCountries(continents) {
var cuntries = [];
for (var i = 0; i < continents.length; i++) {
var a = continents[i];
cuntries = cuntries.concat(a.countries);
}
return cuntries;
}
$scope.GetCountries = function(continents) {
return GetCountries(continents);
}
$scope.GetCities = function(continents) {
var countries = GetCountries(continents);
var cities = [];
for (var i = 0; i < countries.length; i++) {
var a = countries[i];
cities = cities.concat(a.cities);
}
return cities;
}
Html:
<table class="table table-bordered">
<tr>
<th>Continent:</th>
<td ng-repeat="continent in continents" colspan="{{continent.columnSpan}}">{{continent.continent}}</td>
</tr>
<tr>
<th>Country:</th>
<td ng-repeat="country in GetCountries(continents)" colspan="{{country.columnSpan}}">{{country.country}}</td>
</tr>
<tr>
<th>City:</th>
<td ng-repeat="city in GetCities(continents)">{{city.city}}</td>
</tr>
<tr>
<th>Population:</th>
<td ng-repeat="city in GetCities(continents)">{{city.info[0].population}}</td>
</tr>
</table>
jsfiddle: https://jsfiddle.net/2guo5p6d/

Create a table from REST object by setting data in columnar manner

I have a REST service, which returns this object:
[
{
"id": 100,
"value": "2452"
},
{
"id": 100,
"value": "2458"
},
{
"id": 1,
"value": "2457"
},
{
"id": 1,
"value": "2459"
},
{
"id": 4,
"value": "2460"
},
{
"id": 5,
"value": "3458"
}
]
Now, using this GET service, I want the following table to be built in angular and show it in UI.
100 1 4 5
-------------------
2452 2457 2460 3458
2458 2459
i.e. the unique ids should create the header and the list of values associates to each header value will be appended to respective column.
I have tried something with ng-repeat like this:
<table border="1">
<tr>
<th ng-repeat="column in cols">{{column.id}}</th>
</tr>
<tr>
<td ng-repeat="column in cols">
<md-list>
<md-list-item class="md-2-line" ng-repeat="val in column.values">
<md-checkbox ng-model="item.done"></md-checkbox>
<div class="md-list-item-text">
??
</div>
</md-list-item>
</md-list>
</td>
</tr>
But still wondering how to do the same? Please help.
Try use groupBy filter.
var app = angular.module('anApp', ['angular.filter']);
app.controller('aCtrl', function($scope) {
$scope.data = [
{
"id": 100,
"value": "2452"
},
{
"id": 100,
"value": "2458"
},
{
"id": 1,
"value": "2457"
},
{
"id": 1,
"value": "2459"
},
{
"id": 4,
"value": "2460"
},
{
"id": 5,
"value": "3458"
}
];
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
<div ng-app="anApp" ng-controller="aCtrl">
<table border="1">
<tr>
<th ng-repeat="col in data | groupBy: 'id'">{{col[0].id}}</th>
</tr>
<tbody>
<tr>
<td ng-repeat="col in data | groupBy: 'id'">
<table>
<tr ng-repeat="c in col">
<td> {{c.value}}</td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
</div>

How To Total Sum Inside Of Array Values In Angularjs?

I am using MEAN stack in my application with AngularJS as my front-end. How to total sum inside of array values in angularjs , actually we have used ng-repeat inside of one more ng-repeat to fetch the value in table and I got the fetched value like 250 in Sprice then I'm expecting to totalsum the sprice value like as a ans= 250.
My Plunker.
We have used two ng-repeat to get the sprice values in table because sprice is in inside of the [array].
We need to calculate total sum of sprice of value in table.
We have filter functionality to calculate the totalsum of ng-module value if it is in without array.
Actually we dont' know how to use resultValue= in ng-repeat.
For example: sprice value is 250 in table means the totalsum value need to be in 250, if sprice value is 250 and 300 means expecting answer like 550.
Without array totalsum functionality: My Plunker
With array totalsum functionality: My Plunker
My Controller:
.filter('sumOfValue', function () {
return function (data, key) {
debugger;
if (angular.isUndefined(data) && angular.isUndefined(key))
return 0;
var sum = 0;
angular.forEach(data,function(v,k){
sum = sum + parseFloat(v[key]);
});
return sum.toFixed(2);
}
})
My Data:-
$scope.orders = [
{
"_id": "5836b64083d9ce0f0078eae8",
"user": {
"_id": "579bdf6123f37f0e00a40deb",
"displayName": "Table 1"
},
"__v": 8,
"total": "1824",
"ordercar": [],
"orderfood": [
{
"qty": "1",
"confirm": "placed",
"sprice": 250,
"price": 250,
"customise": "With Onion,Without Onion",
"name": "Baasha Pizza"
}
],
"phone": null,
"order_source": "",
"comment": "",
"payment_mode": "",
"nop": null,
"rating": null,
"bill": false,
"complete": false,
"laundry": false,
"clean": false,
"roomservice": false,
"napkin": false,
"waiter": false,
"water": false,
"name": "fgg",
"created": "2016-11-24T09:43:28.413Z",
"isCurrentUserOwner": true
}]
My Html:-
<table ng-table="tableParams" class="table table-bordered ">
<thead>
<tr>
<th rowspan="2">s.no</th>
<th rowspan="2"> sprice </th>
</tr>
</thead>
<tr ng-repeat="order in orders">
<td>{{$index + 1}}</td>
<td ng-repeat="ram in order.orderfood">{{ram.sprice }}</td>
</tr>
<tr>
<td>sum</td>
<td>{{resultValue | sumOfValue:'sprice'}}</td>
</tr>
</table>
*We expecting for total sum in array values.
Used ng-repeat:
<tr ng-repeat="order in orders">
<td>{{$index + 1}}</td>
<td ng-repeat="ram in order.orderfood">{{ram.sprice }}</td>
ng-repeat is not looping properly .. I fixed it .. Check below snippet and also i added one more array to it.......... let me know..
var app = angular.module('plunker', []);
app.filter('sumOfValue', function () {
return function (data, key) {
debugger;
if (angular.isUndefined(data) && angular.isUndefined(key))
return 0;
var sum = 0;
angular.forEach(data,function(v,k){
sum = sum + parseFloat(v[key]);
});
return sum.toFixed(2);
}
}).controller('MainCtrl', function($scope) {
$scope.orders = [
{
"_id": "5836b64083d9ce0f0078eae8",
"user": {
"_id": "579bdf6123f37f0e00a40deb",
"displayName": "Table 1"
},
"__v": 8,
"total": "1824",
"ordercar": [],
"orderfood": [
{
"qty": "1",
"confirm": "placed",
"sprice": 250,
"price": 250,
"customise": "With Onion,Without Onion",
"name": "Baasha Pizza"
},
{
"qty": "2",
"confirm": "placed",
"sprice": 250,
"price": 250,
"customise": "With Onion,Without Onion",
"name": "Baasha Pizza"
}
],
"phone": null,
"order_source": "",
"comment": "",
"payment_mode": "",
"nop": null,
"rating": null,
"bill": false,
"complete": false,
"laundry": false,
"clean": false,
"roomservice": false,
"napkin": false,
"waiter": false,
"water": false,
"name": "fgg",
"created": "2016-11-24T09:43:28.413Z",
"isCurrentUserOwner": true
}]
});
body {
font-size: 14px;
}
table
{
border-collapse:collapse;
}
table, td, th
{
border:1px solid black;
}
td{
padding: 2px;
}
.servicetaxinclusivetrue:before{
color: green!important;
content: "\f00c";
}
.servicetaxinclusivefalse:before{
color: red!important;
content: "\f00d";
}
.servicetaxexclusivetrue:before{
color: green!important;
content: "\f00c";
}
.servicetaxexclusivefalse:before{
color: red!important;
content: "\f00d";
}
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
</head>
<body ng-controller="MainCtrl">
<table ng-table="tableParams" class="table table-bordered ">
<thead>
<tr>
<th rowspan="2">s.no</th>
<th rowspan="2"> sprice </th>
</tr>
</thead>
<tbody ng-repeat="order in orders">
<tr ng-repeat="ram in resultValue=(order.orderfood)">
<td>{{$index + 1}}</td>
<td >{{ram.sprice }}</td>
</tr>
<tr>
<td>sum</td>
<td>{{resultValue | sumOfValue:'sprice'}}</td>
</tr>
</tbody>
</table>
</body>
</html>
Here you can call function using "ng-init", so that angularjs will call function before execution of "ng-repeat".
In that function you can perform iteration and calculate total and hold it in scope variable to display it.

Creating a table header(th) and body(td) from json in angular app

I have an angular app where i am trying to create a table from a json. My json is as follows:
[
{
"campus_id": "321",
"name": "0"
},
{
"campus_id": "231",
"name": "1"
},
{
"campus_id": "123",
"name": "2"
}
]
Generally we will create a table in the html as follows:
<table class="table table-striped">
<tr>
<th>
Campus id
</th>
<th>
Name
</th>
</tr>
<tr ng-repeat="item in items">
<td >
{{item.campus_id}}
</td>
<td >
{{item.name}}
</td>
</tr>
</table>
How do i create even the headers from the json instead of defining them ourselves?
I would add the column headers within the json result like so
columnDefs: [
{field: 'campus_id', displayName: 'Campus ID'},
{field: 'name', displayName: 'Name'}],
data:
[
{
"campus_id": "57911000",
"name": "0"
},
{
"campus_id": "57911001",
"name": "HIGHLAND PARK HIGH SCHOOL"
},
{
"campus_id": "57911007",
"name": "P A S S Learning Center School"
}
]
otherwise you could use the key, value pairing ng-repeat="(key,value) in items" with a filter to return 1 row and then use {{key}}