How To Bind Dynamic List from AngularJS to Html Table? - html

I have a Angular Function
vm.OpenBManageContractBillingReport = function () {
reportService.GetContractBillingList(vm.Search).then(function (response) {
console.log(response);
vm.contractBillingReportList = response;
}, function (err) {
});
};
which gives the output of the list from API and the dynamic list is stored in vm.contractBillingReportList. But the Output may be different According to Start Date and End Date Parameter in vm.search. For Ex:- IF start Date Parameter is 1/1/2018 and End Date Parameter is 31/1/2018 the Result Provides Only One Column January 2018. Similarly, IF start Date Parameter is 1/1/2018 and End Date Parameter is 31/12/2019 the Result Provides 24 Col from January 2018 to December 2019. How Can I bind this data with Header Column in HTML Table?
<div class="clearfix">
<div class="reportTable">
<div class="col-sm-12" style="padding:0;">
<table class="table table-bordered">
<thead>
<tr></tr>
</thead>
<tbody>
<tr ng-repeat="item in vm.contractBillingReportListtrack by $index">
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>

Assuming contractBillingReportList is an array of objects with keys of the object required as header. Just loop for keys in the first element and display those keys as headers.
<tr>
<th ng-repeat="(header, value) in vm.contractBillingReportList[0]">{{header}}</th>
</tr>

Related

How to show this json key value data format into table in angular?

i managed to retrieve non-null json data from backend and i want to display this in table form, can anyone help me, how to display json data like below into table in angular?
{"2020-12-17":
{"tanggal": "2020-12-17", "kurs_jual": "10781.030615606935", "kurs_beli": "10673.605766653045"},
"2020-12-18":
{"tanggal": "2020-12-18", "kurs_jual": "10790.980751228397", "kurs_beli": "10682.253685484742"}
}
this is the html code to display the json data in the table
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Date</th>
<th>Sell</th>
<th>Buy</th>
</tr>
</thead>
<tbody>
<tr *ngFor="forecast_table let data">
<td>{{data['tanggal'].tanggal}}</td>
<td>{{data['tanggal'].kurs_jual}}</td>
<td>{{data['tanggal'].kurs_beli}}</td>
</tr>
</tbody>
</table>
If you have the data in JSON format you could parse the data first. This will parse the json to a js Object.
const obj = JSON.parse(jsonData);
Then you could extract the entries that you want to display in your table.
const rows = Object.values(obj);
Finally use the variable rows to iterate in your table.
<tr *ngFor="let data of rows">
<td>{{data.tanggal}}</td>
<td>{{data.kurs_jual}}</td>
<td>{{data.kurs_beli}}</td>
</tr>
Note that if you got the json response with HTTPClient and the responseType is json, you dont need to do the parsing. The response will be already parsed and you could use it directly as a js Object.

Find total no of items as the result of ng-if?

In my new project,called "Gold loan management system",I need to fetch the ornaments name from ornament table with the specified GLID.GLID is not unique,So we may have more than one row with same GLID and ornament name.ornament name with weight
Now i want to calculate the number of ornaments after perform ng-if.I used "{{ornamentdata.length}}" Which getting the totalno of ornaments in the ornament table.How can we find the total no of ornaments getting as the result of ng-if ?
index.html
<table class="table table-bordered table-hover">
<tr ng-repeat="ornament in ornamentdata" ng-if="ornament.GLID == cstmrdetails.GLID">
<td>{{$index }}</td>
<td>{{ornament.ORNAMENT}}</td>
<td>{{ornament.WEIGHT}}gm</td>
</tr>
</table >
You can use angular filter instead of ng-if ng-repeat expression allows filtered results to be assigned to a variable. This variable will be accessible from current scope so you can use it to count the number of elements in it.
<body ng-controller="MainCtrl">
<table class="table table-bordered table-hover">
<tr ng-repeat="ornament in (filteredItems = (ornamentdata | filter : {GLID: testid}))" >
<td>{{$index }}</td>
<td>{{ornament.ORNAMENT}}</td>
<td>{{ornament.WEIGHT}}gm</td>
</tr>
</table>
<p>Number of filtered items: {{filteredItems.length}}</p>
</body>
DEMO
first add class to ng-repeat raw and then create another raw and call a function. from that get length of the rows
<table class="table table-bordered table-hover">
<tr ng-repeat="ornament in ornamentdata" ng-if="ornament.GLID == cstmrdetails.GLID" class="row-count">
<td>{{$index }}</td>
<td>{{ornament.ORNAMENT}}</td>
<td>{{ornament.WEIGHT}}gm</td>
</tr>
<tr ng-init="getCount()">
<td> count{{count }}</td>
</tr>
</table >
$scope.getCount = function(){
$timeout(function(){
$scope.count = document.getElementsByClassName('row-count').length;
});
}
Make a filter called filterWithCondition
In Your Html
<table class="table table-bordered table-hover">
<tr ng-repeat="ornament in filteredData = (ornamentdata | filterWithCondition:'GLID':cstmrdetails.GLID)">
<td>{{$index }}</td>
<td>{{ornament.ORNAMENT}}</td>
<td>{{ornament.WEIGHT}}gm</td>
</tr>
Filtered Data Count is {{filteredData.length}}
</table >
The Filter is like below
app.filter('filterWithCondition', function() {
return function(items, itemKey, compareWith) {
var filtered = items.filter(function(item){
return item.itemKey == compareWith
})
return filtered;
}
});
plnkr demo Filter Demo

Add pagination after data exceeds limit

I want to add a pagination after the data that can be displayed has exceeded the filter. I have declared that a limit of 6 data can be displayed at a time. I want to display the rest of the data by adding a pagination under the table. How do I go about doing that?
data.html
<section>
<div>
<table style="width:90%" class="table table-bordered" align="center" ng-controller="RetrieveDiaryController">
  <tr>
    <th style="width:40%">Date</th>
    <th style="width:30%">Type</th>
    <th style="width:30%">Level</th>
  </tr>
<tr ng-repeat="d in diaries | orderBy:'date':true | limitTo : limit">
<td>{{d.date | date: "dd-MM-yyyy"}}</td>
<td>{{d.taken}}</td>
<td>{{d.level}}</td>
<tr ng-show="limit" ng-click='limit = undefined'>
</tr>
</table>
</div>
</section>
health.js
.controller('RetrieveDiaryController', ['$scope', 'Diary', function ($scope, Diary) {
$scope.diaries = Diary.find();
$scope.limit = 6;
}])
You can use Angular ui bootstrap pagination directive.
And then add ng-show/ng-hide on the pagination depending on number of results per page.

create dynamic html table with dynamic tr ,td using angularjs

how can I create an html table from a json file, which I do not know the number of columns or the number of rows (the number of row ng-repeat enough),
this json file is editable and the number of column and row change
You would need to load your JSON file into your app with either the $http or $resource service. This is best done in a service, which you would inject whereever you need your data.
this.getJson = function() { // real json get
$http.get('/api/GetJson').then(function(data) {
return data;
});
};
I created a small plunker with a service that holds my fake getJson function which returns the json data with the rows. Then I injected the service into my HomeController and put the rows on the $scope.
$scope.rows = loadJsonService.getFakeJson().rows;
When the rows are on the $scope, you only have to use the ngRepeat directive to create your table structure.
<table class="table table-striped">
<tr class="row" ng-repeat="row in rows">
<th>row {{$index + 1}}</th>
<td class="column" ng-repeat="column in row.column">{{column}}</td>
</tr>
</table>

Knockoutjs' foreach not working when single data has returned

I have a table which is shown below. When multiple data comes, it is shown properly but if a single data come, data isn't shown in the table. I suspect absence of brackets in single data..
Multiple Data Sample:
[{"Id":1,"Name":"Tomato soup","Category":"Groceries","Price":1.39},{"Id":2,"Name":"Yo-yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}]
Single Data sample
{"Id":1,"Name":"Tomato soup","Category":"Groceries","Price":1.39}
Table and scripts:
<script type="text/javascript">
$(document).ready(function () {
function ProductViewModel() {
var self = this;
self.productData = ko.observable();
self.productId = ko.observable();
self.getAllProducts = function () {
$.get('/api/products', {}, self.productData);
};
self.getProductById = function () {
$.get('/api/products/' + self.productId(), {}, self.productData);
};
}
ko.applyBindings(new ProductViewModel());
});
</script>
<input id="txtId" type="text" data-bind="value: productId" />
<button id="btnGetSpeProduct" data-bind="click: getProductById">Get Product By Id</button>
<button id="btnGetProducts" data-bind="click: getAllProducts">Get All Products</button><br />
<table data-bind="with: productData">
<thead>
<tr>
<th>
Name
</th>
<th>
Category
</th>
<th>
Price
</th>
</tr>
</thead>
<tbody data-bind="foreach: $data">
<tr>
<td data-bind="text: Name">
</td>
<td data-bind="text: Category">
</td>
<td data-bind="text: Price">
</td>
</tr>
</tbody>
</table>
The foreach binding can accept either an array or an object specifying various options. In this case, Knockout thinks the object you're giving it is the latter. It will work if you use the object syntax and specify your data using the data option.
<tbody data-bind="foreach: {data: $data}">
Sample: http://jsfiddle.net/mbest/Dta48/
Yes - it has everything to do with the "absence of brackets in single data".
The one with brackets means that it's an array; a list which can can iterate (foreach).
The one without brackets means that it's an object; something which can be stored inside an array, but can not be iterated using foreach.
So, you want it to act like an array so you can iterate over the result. First step, you'll need to use an observableArray instead of observable:
self.productData = ko.observableArray();
Next, you'll need to push the data you $.get to that array, instead of directly binding them.
$.get('/api/products', function(data) {
// Iterate over the data variable, and use
// self.productData.push(ITEM)
// to add it to the array
});
That should do it - good luck!
use observableArray instead of observable
self.productData = ko.observableArray();