How to get the Total value in column in angularjs? - angularjs

I'm new to angularjs. How to get the total amount in the table Total Amount column and display in input textbox? I think this plunker can solve my problem but I can't access it now. http://plnkr.co/edit/CHBm8RCqW5RNZWrzAe5r?p=preview
Here is my table sample
<table>
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Total Amount</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="payment_queue in data | filter:searchFilter">
<td>{{payment_queue.product_name}}</td>
<td>{{payment_queue.sold_quantity}}</td>
<td>{{payment_queue.amount}}</td>
</tr>
</tbody>
</table>
Total Amount: <input type="text value=""> <--- the total amount value goes here...
js
var myApp = angular.module('myApp', ['ngRoute']);
myApp.controller('productsalesController', ['$scope', '$http', function ($scope, $http) {
$scope.data=[];
$http.get("../php/paymentQueuedata.php")
.success(function(data){
$scope.data = data;
})
.error(function() {
$scope.data = "error in fetching data";
});
}]);
php json
<?php
//database settings
$connect = mysqli_connect("localhost", "root", "", "rmsdb");
$result = mysqli_query($connect, "select * from payment_queue");
$data = array();
while ($row = mysqli_fetch_array($result)) {
$data[] = $row;
}
print json_encode($data);
?>

There a way to get the totals without using a function.
Just use ng-init. If you need to allow the list to change or be filtered, use ng-repeat with it to force recalculation of the totals.
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Ext</th>
</tr>
</thead>
<tbody ng-repeat="_ in [ [ search, products ] ]" ng-init="total = 0">
<tr ng-repeat="product in products | filter: search">
<td>{{ product.name }}</td>
<td>{{ product.quantity }}</td>
<td>{{ product.price }}</td>
<td ng-init="$parent.total = $parent.total + (product.price * product.quantity)">${{ product.price * product.quantity }}</td>
</tr>
<tr>
<td><b>Total</b></td>
<td></td>
<td></td>
<td><b>${{ total }}</b></td>
</tr>
</tbody>
</table>
See http://plnkr.co/edit/dLSntiy8EyahZ0upDpgy?p=preview for a workinig example.

My solution to my problem..
in my controller
$scope.totalAmount = function(){
var total = 0;
for(count=0;count<$scope.data.length;count++){
total += parseInt($scope.data[count].total_amount,10);
}
return total;
};
in html
<table>
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Total Amount</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="payment_queue in data | filter:searchFilter">
<td>{{payment_queue.product_name}}</td>
<td>{{payment_queue.sold_quantity}}</td>
<td>{{payment_queue.amount}}</td>
</tr>
</tbody>
</table>
Total Amount: <input type="text value="{{ totalAmount() }}"> <--- the total amount value goes here...

You can do like this. This is good solution for your problem.
index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link data-require="bootstrap-css#*" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.22/angular.js" data-semver="1.2.22"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<table class="table table-striped">
<tbody>
<tr ng-repeat="item in items">
<td>{{item.name}}</td>
<td>{{item.years}}</td>
<td>{{item.amount}}</td>
<td>{{item.interest}}%</td>
</tr>
<tr>
<td>Total:</td>
<td>{{getTotal('years')}}</td>
<td>{{getTotal('amount')}}</td>
<td>{{getTotal('interest')}}</td>
</tr>
</tbody>
</table>
</body>
</html>
app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [
{name: 'xxx', amount: 13, years: 3, interest: 2},
{name: 'yyy', amount: 23, years: 4, interest: 3},
{name: 'zzz', amount: 123, years: 4, interest: 4}
];
$scope.getTotal = function(int) {
var total = 0;
angular.forEach($scope.items, function(el) {
total += el[int];
});
return total;
};
});
you can use this url also. Thank you !!!
http://plnkr.co/edit/CHBm8RCqW5RNZWrzAe5r?p=preview

Related

Calculate the total of prices in angularjs

I am newbie in Angular. I am trying to print the gross total of the products in the bill. While calculating the product total, the value of qty is given by the user. The code for calculating product total is working fine but when I am calculating the gross total, it takes the default value as 1 only and not the value given by the user.
The server is responding with the product details like code, name, price, and gst.The quantity is entered by user.
I searched, but everywhere the quantity was coming from server's response.
Here is my code for billPage:
<body>
<div class="container" ng-controller="billCtrl">
<h1>Billing Section</h1>
<input class="form-control" ng-model="search"><br>
<button class="btn btn-primary" ng-click="searchProduct(search)">Search Product</button>
<table class="table">
<thead>
<tr>
<th>Product Code</th>
<th>Product Name</th>
<th>Product Price</th>
<th>GST(%)</th>
<th>Quantity</th>
<th>Product Total</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in billing" ng-init="model = [{qty:1}]">
<td>{{product.code}}</td>
<td>{{product.name}}</td>
<td>{{product.price}}</td>
<td>{{product.gst}}</td>
<td><input type="number" ng-model="model[$index].qty" ng-required class="form-control"></td>
<td>{{(product.price+(product.gst*product.price/100)) * model[$index].qty }}</td>
</tr>
<tr>
<td colspan="5" style="text-align:right">Gross Total</td>
<td>{{total()}}</td>
</tr>
</tbody>
</table>
</div>
Code for BillCtrl.js
var myApp = angular.module('myApp', ["ngRoute"]);
myApp.controller('billCtrl', ['$scope', '$http', function($scope, $http) {
console.log("Hello World from bill");
$scope.billing = [];
$scope.searchProduct = function(id) {
console.log("search");
$http.get('/billing/' + id).success(function(response) {
$scope.billing.push(response[0]);
});
}
$scope.total = function() {
console.log($scope.model[0].qty);
var total = 0;
angular.forEach($scope.billing, function(product) {
total += (product.price + (product.price * product.gst / 100)) * $scope.model.qty;
})
console.log(total);
return total;
}
}])
You can have the total logic in UI and addup the total in controller
Here is the working example
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link data-require="bootstrap#3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script data-require="angular.js#1.6.6" data-semver="1.6.6" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js" type="text/javascript"></script>
<script>
(function() {
angular.module("testApp", ['ui.bootstrap']).controller('billCtrl', ['$scope', '$http', function($scope, $http) {
console.log("Hello World from bill");
$scope.model = undefined;
$scope.billing = [];
$scope.searchProduct = function(id) {
console.log("search");
/*$http.get('/billing/' + id).success(function(response) {
$scope.billing.push(response[0]);
});*/
$scope.billing = [{"code":"a1","name":"a1","price":100,"gst":0.1},{"code":"a2","name":"a2","price":200,"gst":0.2},{"code":"a3","name":"a3","price":300,"gst":0.3},{"code":"a4","name":"a4","price":400,"gst":0.4}];
}
$scope.total = function() {
//console.log($scope.model[0].qty);
var total = 0;
angular.forEach($scope.billing, function(product, index) {
total += product.total;
})
console.log(total);
return total;
}
}]);
}());
</script>
<style></style>
</head>
<body ng-app="testApp">
<div class="container" ng-controller="billCtrl">
<h1>Billing Section</h1>
<input class="form-control" ng-model="search"><br>
<button class="btn btn-primary" ng-click="searchProduct(search)">Search Product</button>
<table class="table">
<thead>
<tr>
<th>Product Code</th>
<th>Product Name</th>
<th>Product Price</th>
<th>GST(%)</th>
<th>Quantity</th>
<th>Product Total</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="product in billing" ng-init="model = [{qty:1}];">
<td>{{product.code}}</td>
<td>{{product.name}}</td>
<td>{{product.price}}</td>
<td>{{product.gst}}</td>
<td><input type="number" ng-model="model[$index].qty" ng-required class="form-control"
ng-change="product.total = model[$index].qty?(product.price+(product.gst*product.price/100)) * model[$index].qty:0"
ng-init="product.total = model[$index].qty?(product.price+(product.gst*product.price/100)) * model[$index].qty:0"></td>
<td>{{product.total}}</td>
</tr>
<tr>
<td colspan="5" style="text-align:right">Gross Total</td>
<td>{{total()}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

How to calculate sum of html table column from a dynamically created HTML Table using AngularJS?

In the attached code snippet I want to calculate the total of Net Amount from all rows using AngularJS.
Your quick assistance in this regards will be highly appreciated.
<html ng-app="MyApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Add Rows</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<script>
angular.module('MyApp', [])
.controller('MainController', ['$scope', '$http',
function ($scope, $http) {
$scope.rows = ['Row 1'];
$scope.counter = 3;
$scope.calculateTableSum = function (dQuantityIssued, dUnitPrice)
{
$scope.GrossTotal = dQuantityIssued * dUnitPrice;
}
//Adding Row
$scope.addRow = function () {
$scope.rows.push('Row ' + $scope.counter);
$scope.counter++;
}
//Removing Row
$scope.removeRow = function (rowIndex) {
$scope.rows.splice(rowIndex, 1);
}
} ]);
</script>
Add Row {{counter}}
<table border="1">
<thead>
<tr>
<th>
</th>
<th>
Product
</th>
<th>
Description
</th>
<th>
Qty Issued
</th>
<th>
Unit Price
</th>
<th>
Gross Total
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(rowIndex,rowContent) in rows">
<td>
<input type="button" value="Remove" class="btn btn-primary" ng-click="removeRow(rowIndex)" />
</td>
<td>
<input type="text"></input>
</td>
<td>
<input type="text"></input>
</td>
<td>
<input ng-model="QtyIssued" type="number"/>
</td>
<td>
<input ng-model="UnitPrice" type="number" ng-change="calculateTableSum(QtyIssued,UnitPrice)" />
</td>
<td>
<input ng-model="GrossTotal" type="number" ng-bind="QtyIssued*UnitPrice" />
</td>
</tr>
</tbody>
<tfoot>
</tfoot>
</table>
<p>
Net Amount Total = {{NetAmount}}
</p>
Please go through this:
<table ng-controller="SubTotalCtrl">
<thead>
<tr><th ng-repeat="(key, th) in head">{{th}}</th></tr>
</thead>
<tbody>
<tr ng-repeat="row in body">
<td><input ng-model="row.a"></input></td>
<td><input ng-model="row.b"></input></td>
<td><input ng-model="row.c"></input></td>
</tr>
</tbody>
<tfoot>
<tr ng-repeat="(perc, sum) in grouppedByPercentage()">
<td></td>
<td><span>Subtotal for {{perc}}%</span></td>
<td>{{sum * perc / 100.0}}</td>
</tr>
</tfoot>
</table>
angular
.module('myApp', [])
.controller('SubTotalCtrl', function ($scope) {
// data
$scope.head = {
a: "Amount",
b: "Percent",
c: "Percent"
};
$scope.body = [{
a: "1000",
b: "5",
c: "10"
}, {
a: "2000",
b: "0",
c: "5"
}, {
a: "3000",
b: "10",
c: "20"
}];
$scope.grouppedByPercentage = function () {
var groups = {};
$scope.body.forEach(function (row) {
['b', 'c'].forEach(function (key) {
var perc = row[key];
if (perc === '0') { return; } // ignore 0 percentage
if (!groups[perc]) {
groups[perc] = 0;
}
groups[perc] += parseInt(row.a);
// use `parseFloat()` if you want decimal points
});
});
return groups;
};
});
http://jsfiddle.net/ExpertSystem/LD7QS/1/
It will answer all your questions.

How do I apply the multiple orderBy filter with array in AngularJs?

I have to filter the list of an array using the orderBy filter. In my case, having multiple orderBy is not working, only with a single orderBy is it working properly. How do I implement that?
//here we create the product array and display the array in the HTML page.
var app=angular.module("App",[]);
app.controller("Cont",function($scope){
var product = [
{:"110",ename:"Harry",esalary:"25000",ecity:"Agar"},
{pid:"109",ename:"potter",esalary:"11000",ecity:"US"},
{pid:"101",ename:"Peter",esalary:"1200",ecity:"London"},
{pid:"104",ename:"Janifer",esalary:"12000",ecity:"Bejing"},
{pid:"103",ename:"Selena",esalary:"35000",ecity:"England"},
{pid:"102",ename:"Lokesh",esalary:"32500",ecity:"Malwa"},
{pid:"108",ename:"Gotm",esalary:"8910",ecity:"Ujain"},
{pid:"106",ename:"Soni",esalary:"16000",ecity:"bhopal"},
]
$scope.products=product;
});
<html>
<head>
<script src="angular.min.js"></script>
<script src="controller.js"></script>
</head>
<body ng-app="App" ng-controller="Cont">
<form align="center">
<table align="center" border="2">
<thead>
<tr>
<th>pid</th>
<th>ename</th>
<th>esalary</th>
<th>ecity</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in products | orderBy:['pid','ename','esalary']">
<td>{{x.pid}}</td>
<td>{{x.ename | uppercase}}</td>
<td>{{x.esalary }}</td>
<td>{{x.ecity}}</td>
</tr>
</tbody>
</table>
</form>
</body
</html>
var app = angular.module("App", []);
app.controller("Cont", function($scope) {
var product = [
{
'pid': "110",
'ename': "Harry",
'esalary': "25000",
'ecity': "Agar"
},
{
'pid': "109",
'ename': "potter",
'esalary': "11000",
'ecity': "US"
},
{
'pid': "101",
'ename': "Peter",
'esalary': "1200",
'ecity': "London"
},
{
'pid': "104",
'ename': "Janifer",
'esalary': "12000",
'ecity': "Bejing"
}]
$scope.products = product;
});
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.4.7" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
</head>
<body ng-app="App" ng-controller="Cont">
<form align="center">
<table align="center" border="2">
<thead>
<tr>
<th>pid</th>
<th>ename</th>
<th>esalary</th>
<th>ecity</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in products | orderBy:'pid' | orderBy:'ename'">
<td>{{x.pid}}</td>
<td>{{x.ename | uppercase}}</td>
<td>{{x.esalary }}</td>
<td>{{x.ecity}}</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
Try this :
<tr ng-repeat="x in products | orderBy:['pid','ename']">
<td>{{x.pid}}</td>
<td>{{x.ename | uppercase}}</td>
<td>{{x.esalary }}</td>
<td>{{x.ecity}}</td>
</tr>

How to Sort the Auto Increment Serial number Column in angularJS Table?

How to Sort the Auto Increment Serial number Column in angularjs Table ?
I'm having Serial Number Column with Auto Increament, I need to Sort the Column.
My Source Code is
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<thead>
<tr>
<th>S.No.</th>
<th>Name</th>
<th>D.O.B.</th>
</tr>
</thead>
<tr ng-repeat="x in names | orderBy:orderByField:reverseSort">
<td>{{ $index + 1 | number }}</td>
<td>{{ x.Name }}</td>
<td><span ng-if="x.DOB">{{ formatDate(x.DOB) | date:'dd-MM-yyyy' }}</span></td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.names = [
{ Name: 'Jani', DOB: '' },
{ Name: 'Hege', DOB: '1995-05-07' },
{ Name: 'Kai', DOB: '1995-08-24' }
];
$scope.formatDate = function (date) {
return new Date(date);
};
});
</script>
</body>
</html>
The Auto Increment Part is {{ $index + 1 }} within <td> tag.
In Angular 2+ you can use like this:
<div *ngFor="let item of items; let ndx = index">
<div>{{ndx+1}}</div>
</div>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
$scope.orderByMe = function(x) {
$scope.myOrderBy = x;
}
});
table tr th{
cursor:pointer;
}
table tr th:hover{
background:#ddd;
}
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<p>Click the table headers to change the sorting order:</p>
<div ng-app="myApp" ng-controller="namesCtrl">
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('num')">Sl.No</th>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy">
<td>{{$index + 1}}</td>
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>
</div>
</body>
</html>
You can use like this
<tr *ngFor="let user of userList ;let i = index">
<td>{{i+1}}</td>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
<td>{{user.userName}}</td>
<td>{{user.email}}</td>
</tr>

AngularJS Filter (Function and input search together)

I want to use filter function and input search at the same time by using AngularJS. I can able to do with multiple functions. But I'm getting some errors while I add an textbox for search. Is there any way to do this? I tried some ways but no one did not work.
Thanks in advance.
Example code is below
var app = angular.module("app", []),
url = "http://www.filltext.com/?rows=50&pretty=true&fName={firstName}&age=[18,19,20,21]";
app.controller("controller", function($scope, $http) {
$http.get(url)
.success(function(resp) {
$scope.list = resp;
});
$scope.filterAge = function(item) {
return item.age > 19;
};
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<meta charset="utf-8">
<title>AngularJS Filter</title>
</head>
<body ng-controller="controller">
<div class="container">
<br>
<input type="text" ng-model="search" placeholder="Search..." />
<table class="table table-striped">
<thead>
<th>Name</th>
<th>Age</th>
</thead>
<tbody>
<tr ng-repeat="item in list | filter: filterAge">
<td>{{ item.fName }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
You should add custom filter to angular module instead adding filter function to your controller. This is the example:
CustomFilter:
.filter('filterByAge', function filterByAge() {
return function(array, age) {
var filteredArray = [];
angular.forEach(array, function(item) {
if (item.age > age) {
filteredArray.push(item);
}
});
return filteredArray;
}
});
HTML
<input type="text" ng-model="search" placeholder="Search..." />
<table class="table table-striped">
<thead>
<th>Name</th>
<th>Age</th>
</thead>
<tbody>
<tr ng-repeat="item in list | filter: search | filterByAge:19">
<td>{{ item.fName }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
$scope.$watch('search', function (data) {
//sorting logic
})
Watcher is waiting for any action taken on search filed then the function is executed.

Resources