I am new to Angular JS .I have an Wcf Rest Service to get all the records from the database and its is working but i am trying to add the grand total at the bottom of the page but i can not do it . insated of showing grand totla its showing the text message . I am trying to add the amount Clomun..
Here is my script code ..
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
$scope.OperType = 1;
$scope.Account_Number = "";
$scope.Account_Holder_Name = "";
$scope.Amount = "";
$scope.Sort_Code = "";
$scope.Transcation_Type = "";
$scope.Date = "";
GetAllRecords();
//To Get All Records
function GetAllRecords() {
var promiseGet = myService.getAllStudent();
promiseGet.then(function (pl) { $scope.Users = pl.data },
function (errorPl) {
$log.error('Some Error in Getting Records.', errorPl);
});
}
//$scope.getTotal = function () {
// var total = 0;
// for (var i = 0; i < $scope.cart.Amount.length; i++) {
// var product = $scope.cart.Users[i];
// total += (user.Amount + user.Amount);
// }
// return total;
//}
}]);
app.service("myService", function ($http) {
this.getAllStudent = function () {
return $http.get("http://localhost:52098/HalifaxIISService.svc/GetCreateCurrentAccountDepositList");
}
})
Here is my HTML CODE ..
#{
Layout = null;
}
<!DOCTYPE html>
<html data-ng-app="WebClientModule">
<head>
<meta name="viewport" content="width=device-width" />
<title>TotalDeposit</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/RegistrationScript/DepositTotal.js"></script>
</head>
<body>
<table ng-init="items.total = {}" id="tblContainer" data-ng-controller="Web_Client_Controller">
<tr>
<td>
<table style="border: solid 2px Green; padding: 5px;">
<tr style="height: 30px; background-color: skyblue; color: maroon;">
<th></th>
<th>Account Number</th>
<th>Account Holder Name</th>
<th>Amount</th>
<th>Sort Code</th>
<th>Transcation Type</th>
<th>Date</th>
<th></th>
<th></th>
</tr>
<tbody data-ng-repeat="user in Users">
<tr>
<td></td>
<td><span>{{user.Account_Number}}</span></td>
<td><span>{{user.Account_Holder_Name}}</span></td>
<td><span>{{user.Amount}}</span></td>
<td><span>{{user.Sort_Code}}</span></td>
<td><span>{{user.Transcation_Type}}</span></td>
<td><span>{{user.Date}}</span></td>
</tr>
</tbody>
<td ng-init="Users.total.amount = items.total.amount + item.amount">{{user.amount}}</td>
</table>
</td>
</tr>
<tr>
<td>Total</td>
<td>{{items.total.amount}}</td>
</tr>
</table>
</body>
</html>
Here is the screen shot when o run the application.
Create a function to get the grand total something like
$scope.grandTotal= function(){
return $scope.users.reduce(function(a, b){
return a + b.amount;
},0);
}
Then in html
<tr>
<td>Total</td>
<td>{{grandTotal()}}</td>
</tr>
Working demo
reference for array.reduce
Related
I'm trying to take data from a JSON file and create a html table, I am able to create the first row of the table using the below code:
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
</head>
<body>
<table id='overview-table'>
<tr>
<th>owner Name</th>
<th>date</th>
<th>shares Held</th>
<th>shares Change</th>
<th>shares ChangePCT</th>
<th>market Value</th>
</tr>
<tr>
<td id='ownerName'></td>
<td id='date'></td>
<td id='sharesHeld'></td>
<td id='sharesChange'></td>
<td id='sharesChangePCT'></td>
<td id='marketValue'></td>
</tr>
</table>
<script type="text/javascript">
const requestUrl = 'https://api.npoint.io/b15e98da7b057152618b';
const requestJSON = async url => {
const response = await (await fetch(url)).json();
ownerName.innerHTML = response.ownerName[0];
date.innerHTML = response.date[0];
sharesHeld.innerHTML = response.sharesHeld[0];
sharesChange.innerHTML = response.sharesChange[0];
sharesChangePCT.innerHTML = response.sharesChangePCT[0];
marketValue.innerHTML = response.marketValue[0];
}
requestJSON(requestUrl);
</script>
</body>
</html>
The first row is created successfully, however if I want to include more rows then I would have to repeat the same bunch of code over again. Is there not a more efficient way of doing this?
Here is my JSON data:
{
"ownerName":{
"0":"VANGUARD GROUP INC",
"1":"BLACKROCK INC.",
"2":"BERKSHIRE HATHAWAY INC",
"3":"STATE STREET CORP",
"4":"FMR LLC",
"5":"GEODE CAPITAL MANAGEMENT, LLC",
"6":"PRICE T ROWE ASSOCIATES INC \/MD\/",
"7":"MORGAN STANLEY",
"8":"NORTHERN TRUST CORP",
"9":"BANK OF AMERICA CORP \/DE\/"
},
"date":{
"0":"09\/30\/2022",
"1":"09\/30\/2022",
"2":"09\/30\/2022",
"3":"09\/30\/2022",
"4":"09\/30\/2022",
"5":"09\/30\/2022",
"6":"09\/30\/2022",
"7":"09\/30\/2022",
"8":"09\/30\/2022",
"9":"09\/30\/2022"
},
"sharesHeld":{
"0":"1,272,378,901",
"1":"1,020,245,185",
"2":"894,802,319",
"3":"591,543,874",
"4":"350,900,116",
"5":"279,758,518",
"6":"224,863,541",
"7":"182,728,771",
"8":"176,084,862",
"9":"142,260,591"
},
"sharesChange":{
"0":"-4,940,153",
"1":"-8,443,132",
"2":"0",
"3":"-6,634,650",
"4":"6,582,142",
"5":"1,502,326",
"6":"-13,047,242",
"7":"278,206",
"8":"-3,744,060",
"9":"-6,873,324"
},
"sharesChangePCT":{
"0":"-0.387%",
"1":"-0.821%",
"2":"0%",
"3":"-1.109%",
"4":"1.912%",
"5":"0.54%",
"6":"-5.484%",
"7":"0.152%",
"8":"-2.082%",
"9":"-4.609%"
},
"marketValue":{
"0":"$192,498,204",
"1":"$154,352,894",
"2":"$135,374,643",
"3":"$89,494,673",
"4":"$53,087,679",
"5":"$42,324,666",
"6":"$34,019,605",
"7":"$27,645,036",
"8":"$26,639,879",
"9":"$21,522,605"
},
You can use a loop and duplicate a row template each time. Rather than using IDs for your table cells, you'll want to use classes as they'll be repeated throughout the document.
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
</head>
<body>
<table id='overview-table'>
<tr>
<th>owner Name</th>
<th>date</th>
<th>shares Held</th>
<th>shares Change</th>
<th>shares ChangePCT</th>
<th>market Value</th>
</tr>
<tr id='rowTemplate'>
<td class='ownerName'></td>
<td class='date'></td>
<td class='sharesHeld'></td>
<td class='sharesChange'></td>
<td class='sharesChangePCT'></td>
<td class='marketValue'></td>
</tr>
</table>
<script type="text/javascript">
const requestUrl = 'https://api.npoint.io/b15e98da7b057152618b';
const requestJSON = async url => {
const response = await (await fetch(url)).json();
const limit = Math.max(...Object.keys(response.ownerName)) + 1;
for(let index = 0; index < limit; index++)
{
let newRow = rowTemplate.cloneNode(true);
newRow.id = '';
newRow.querySelector('.ownerName').innerHTML = response.ownerName[index];
newRow.querySelector('.date').innerHTML = response.date[index];
newRow.querySelector('.sharesHeld').innerHTML = response.sharesHeld[index];
newRow.querySelector('.sharesChange').innerHTML = response.sharesChange[index];
newRow.querySelector('.sharesChangePCT').innerHTML = response.sharesChangePCT[index];
newRow.querySelector('.marketValue').innerHTML = response.marketValue[index];
rowTemplate.parentNode.appendChild(newRow);
}
rowTemplate.parentNode.removeChild(rowTemplate); // Tidy up and remove the template
}
requestJSON(requestUrl);
</script>
</body>
</html>
I am trying in AngularJS to display the employee details with dynamic filter (Location - Value like US, IN, CA etc..) as checkboxlist based on the data got it from DB. I have tried multiple ways without success. Please help to achive the dynamic filter from Checkboxlist.
My code sample below:
<html>
<body ng-app="myapp" ng-controller="myController">
<div >Location</div>
<table>
<tbody>
<tr ng-repeat="empL in EmpResult | unique : 'Location'">
<td>
<span>
<input type="checkbox" ng-model="loc" value={{empL.Location}} />
{{empL.Location}}
</span>
</td>
</tr>
</tbody>
</table>
<table align="left" style="width: 100%" class="table">
<thead>
<tr>
<th align="left" style="width: 30%">Employee</th>
<th align="left" style="width: 20%">Address</th>
<th align="left" style="width: 15%">Location</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="empN in EmpResult | filter : loc">
<td align="left" style="width: 30%">{{empN.EmpName}}</td>
<td align="left" style="width: 10%">{{empN.Address}}</td>
<td align="left" style="width: 15%">{{empN.Location}}</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
var myapp = angular.module('myapp', ['ui.unique'])
.controller("myController", function ($scope, $http) {
$http({
method: 'Get',
params: { strName: $scope.strName },
url: 'Emp.asmx/GetEmpbyName'
}).then(function (response) {
$scope.EmpResult = response.data;
})
});
</script>
</body>
</html>
I've created a mirror of your issue, please take a look at it. I think it should work in your situation.
Plunker
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
</head>
<body ng-app="myApp" ng-controller="myController">
<div ng-init="init()">Location</div>
<table>
<tbody>
<tr ng-repeat="empL in locations">
<td>
<span>
<input type="checkbox" name="locations + $index" data-ng-model="locChkBox.loc[$index]" ng-true-value="'{{empL}}'" ng-false-value="" ng-change="repopulate()"/>
{{empL}}
</span>
</td>
</tr>
</tbody>
</table>
<table align="left" style="width: 100%" class="table">
<thead>
<tr>
<th align="left" style="width: 30%">Employee</th>
<th align="left" style="width: 20%">Address</th>
<th align="left" style="width: 15%">Location</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="empN in EmpResult | filter : locFilter ">
<td align="left" style="width: 30%">{{empN.EmpName}}</td>
<td align="left" style="width: 10%">{{empN.Address}}</td>
<td align="left" style="width: 15%">{{empN.Location}}</td>
</tr>
</tbody>
</table>
<script>
var myApp = angular.module('myApp', []);
myApp.controller("myController", ['$scope', '$http', function($scope, $http) {
$scope.locations = [];
$scope.search = {};
$scope.locChkBox = {};
$scope.locChkBox.loc = [];
$scope.locChkBox.loc.push("US");
$scope.init = function() {
$scope.EmpResult = JSON.parse('[{"EmpName":"jondoe","Address":"dummyAddr","Location":"US"},{"EmpName":"jondoe2","Address":"dummyAddr2","Location":"IN"},{"EmpName":"jondoe3","Address":"dummyAddr3","Location":"CA"},{"EmpName":"jondoe4","Address":"dummyAddr4","Location":"US"},{"EmpName":"jondoe5","Address":"dummyAddr5","Location":"IN"},{"EmpName":"jondoe6","Address":"dummyAddr6","Location":"CA"},{"EmpName":"jondoe7","Address":"dummyAddr7","Location":"US"},{"EmpName":"jondoe8","Address":"dummyAddr8","Location":"IN"},{"EmpName":"jondoe9","Address":"dummyAddr9","Location":"CA"},{"EmpName":"jondoe11","Address":"dummyAddr11","Location":"US"},{"EmpName":"jondoe22","Address":"dummyAddr22","Location":"IN"}]');
var flags = [],
output = [],
l = $scope.EmpResult.length,
i;
for (i = 0; i < l; i++) {
if (flags[$scope.EmpResult[i].Location]) continue;
flags[$scope.EmpResult[i].Location] = true;
output.push($scope.EmpResult[i].Location);
}
$scope.locations = output;
};
$scope.locFilter = function(item) {
for (var i = 0; i < $scope.locChkBox.loc.length; i++) {
if (item.Location === $scope.locChkBox.loc[i])
return true;
}
return false;
};
}]);
</script>
</body>
</html>
EDIT 2
This code will display all the values if none of the checkbox is selected.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
</head>
<body ng-app="myApp" ng-controller="myController">
<div ng-init="init()">Location</div>
<table>
<tbody>
<tr ng-repeat="empL in locations">
<td>
<span>
<input type="checkbox" name="locations + $index" data-ng-model="locChkBox.loc[$index]" ng-true-value="'{{empL}}'" ng-false-value="" ng-change="repopulate()"/>
{{empL}}
</span>
</td>
</tr>
</tbody>
</table>
<table align="left" style="width: 100%" class="table">
<thead>
<tr>
<th align="left" style="width: 30%">Employee</th>
<th align="left" style="width: 20%">Address</th>
<th align="left" style="width: 15%">Location</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="empN in EmpResult | filter : locFilter ">
<td align="left" style="width: 30%">{{empN.EmpName}}</td>
<td align="left" style="width: 10%">{{empN.Address}}</td>
<td align="left" style="width: 15%">{{empN.Location}}</td>
</tr>
</tbody>
</table>
<script>
var myApp = angular.module('myApp', []);
myApp.controller("myController", ['$scope', '$http', function($scope, $http) {
$scope.locations = [];
$scope.search = {};
$scope.locChkBox = {};
$scope.locChkBox.loc = [];
$scope.init = function() {
$scope.EmpResult = JSON.parse('[{"EmpName":"jondoe","Address":"dummyAddr","Location":"US"},{"EmpName":"jondoe2","Address":"dummyAddr2","Location":"IN"},{"EmpName":"jondoe3","Address":"dummyAddr3","Location":"CA"},{"EmpName":"jondoe4","Address":"dummyAddr4","Location":"US"},{"EmpName":"jondoe5","Address":"dummyAddr5","Location":"IN"},{"EmpName":"jondoe6","Address":"dummyAddr6","Location":"CA"},{"EmpName":"jondoe7","Address":"dummyAddr7","Location":"US"},{"EmpName":"jondoe8","Address":"dummyAddr8","Location":"IN"},{"EmpName":"jondoe9","Address":"dummyAddr9","Location":"CA"},{"EmpName":"jondoe11","Address":"dummyAddr11","Location":"US"},{"EmpName":"jondoe22","Address":"dummyAddr22","Location":"IN"}]');
var flags = [],
output = [],
l = $scope.EmpResult.length,
i;
for (i = 0; i < l; i++) {
if (flags[$scope.EmpResult[i].Location]) continue;
flags[$scope.EmpResult[i].Location] = true;
output.push($scope.EmpResult[i].Location);
}
$scope.locations = output;
};
$scope.locFilter = function(item) {
if($scope.locChkBox.loc.isNull()) return true;
for (var i = 0; i < $scope.locChkBox.loc.length; i++) {
if (item.Location === $scope.locChkBox.loc[i])
return true;
}
return false;
};
}]);
Array.prototype.isNull = function (){
return this.join().replace(/,/g,'').length === 0;
};
</script>
</body>
</html>
<tr ng-repeat="empN in EmpResult | filter : 'loc'">
Use the filter with single quotes also. This will filter the data from checkbox.
I am trying to learn AngularJS and started my first code sample to get github repos of a user.
My html page is like this:
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="gitHubRepoController">
{{error}}
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Full Name</th>
<th>HTML Url</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="repo in repos">
<td>{{repo.name}}</td>
<td>{{repo.full_name}}</td>
<td>{{repo.html_url}}</td>
<td>{{repo.description}}</td>
</tr>
</tbody>
</table>
</body>
</html>
and my controller is like this
(function() {
var app = angular.module("githubViewer",[]);
var gitHubRepoController = function($scope, $http){
$http.get("https://api.github.com/users/lakshman553/repos")
.then(onDataDownloaded, onError);
var onDataDownloaded = function(response) {
console.log(response.data);
$scope.repos = response.data;
};
$scope.error = "some value";
var onError = function(reason) {
$scope.error = reason;
};
};
app.controller("gitHubRepoController",gitHubRepoController);
})();
AngularJS is loaded as it is showing the {{error}} is being shown on the screen as some value
the table header is properly loaded but nothing else is shown. Even the url is returning data when seen in broswer.
There are no errors in the console also.
Where am i going wrong?
You need to move the declaration of your promise handlers (onDataDownloaded, onErro) to before you try to use them. Plnkr
(function() {
console.log('this is the app')
var app = angular.module("githubViewer",[]);
var gitHubRepoController = function($scope, $http){
var onDataDownloaded = function(response) {
$scope.repos = response.data;
};
var onError = function(reason) {
$scope.error = reason;
};
$http.get("https://api.github.com/users/lakshman553/repos")
.then(onDataDownloaded, onError);
};
app.controller("gitHubRepoController",gitHubRepoController);
})();
Problem is with your controller.
Your HTML:
<body ng-controller="CustomersController">
{{error}}
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Full Name</th>
<th>HTML Url</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="repo in repos">
<td>{{repo.name}}</td>
<td>{{repo.full_name}}</td>
<td>{{repo.html_url}}</td>
<td>{{repo.description}}</td>
</tr>
</tbody>
</table>
</body>
HTML should be:
<body ng-controller="gitHubRepoController">
{{error}}
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Full Name</th>
<th>HTML Url</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="repo in repos">
<td>{{repo.name}}</td>
<td>{{repo.full_name}}</td>
<td>{{repo.html_url}}</td>
<td>{{repo.description}}</td>
</tr>
</tbody>
</table>
</body>
JS:
(function() {
var app = angular.module("githubViewer",[]);
var gitHubRepoController = function($scope, $http){
var onDataDownloaded = function(response) {
console.log(response.data);
$scope.repos = response.data;
};
$scope.error = "some value";
var onError = function(reason) {
$scope.error = reason;
};
$http.get("https://api.github.com/users/lakshman553/repos")
.then(onDataDownloaded, onError);
};
app.controller("gitHubRepoController",gitHubRepoController);
})();
You have given the controller as ng-controller="CustomersController" which is wrong. If you checked the console it shows you the error clearly.
Hope this will help you.
Trying to store all the information that getting from JSONP in the table.
Have done the test with 'alert' to make sure that there are more info that only one line and can see that there are more info that one.
But when run it, in the table I can see title row and first row.
Can somebody correct my error?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
</script>
<script>
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.example.com/v1/deal/hotel?apikey=xxx&format=JSONP",
dataType : "jsonp",
success : function(parsed_json) {
$.each(parsed_json.Result, function( index, value ) {
alert( index + ": " + value.StarRating + " , "+ value.Url);
});
var from = parsed_json['Result'][0]['StartDate'];
document.getElementById("from").innerHTML = from;
var from = parsed_json['Result'][0]['StartDate'];
document.getElementById("from").innerHTML = from;
var to = parsed_json['Result'][0]['EndDate'];
document.getElementById("to").innerHTML = to;
var nights = parsed_json['Result'][0]['NightDuration'];
document.getElementById("nights").innerHTML = nights;
var currency = parsed_json['Result'][0]['CurrencyCode'];
document.getElementById("currency").innerHTML = currency;
var price = parsed_json['Result'][0]['Price'];
document.getElementById("price").innerHTML = price;
var link = parsed_json['Result'][0]['Url'];
document.getElementById("link").innerHTML = link;
//how to represent enlaces
var city = parsed_json['Result'][0]['City'];
document.getElementById("city").innerHTML = city;
var country = parsed_json['Result'][0]['CountryCode'];
document.getElementById("country").innerHTML = country;
var stars = parsed_json['Result'][0]['StarRating'];
document.getElementById("stars").innerHTML = stars;
}
});
});
</script>
</head>
<body>
<table id="t">
<tr>
<th>Start date</th>
<th>End date</th>
<th>Nights</th>
<th>Currency</th>
<th>Price</th>
<th>Link</th>
<th>City</th>
<th>Country Code</th>
<th>Star Rating</th>
</tr>
<tr>
<td id="from"></td>
<td id="to"></td>
<td id="nights"></td>
<td id="currency"></td>
<td id="price"></td>
<td id="link"></td>
<td id="city"></td>
<td id="country"></td>
<td id="stars"></td>
</tr>
</table>
</body>
</html>
The result of the Ajax callback is:
callback({"Errors":[],"Result":[{"FoundDate":"2013-12-04T16:11:36-08:00","CurrencyCode":"USD","NightDuration":"2.0","EndDate":"12/08/2013","Headline":"Cairo 5 Star Hotel, $36/night","IsWeekendStay":"true","Price":"36.0","StartDate":"12/06/2013","Url":"http‍://www.example.com/hotel/...&startDate=12/06/2013&endDate=12/08/2013&bid=0&sid=0","City":"Cairo","CountryCode":"EG","NeighborhoodLatitude":"30.0152","NeighborhoodLongitude":"31.1756","Neighborhood":"Cairo West - Giza","StarRating":"5.0","StateCode":"EG"},{"FoundDate":"2013-12-04T14:51:44-08:00",
If you have more than one line in result, then you have to -
Loop through it in the callback. You are not looping through it now. You are looping only for alert.
Dynamically create a new row in table for each line. You can clone the exiting tr for this using jquery clone method. But replace the id with 'class`.
Add data to that row pertaining to the line by modifying innerHtml of each td in the newly created row.
Finally, Append the row to the table
HTML -
<table id="t">
<tr>
<th>Start date</th>
<th>End date</th>
<th>Nights</th>
<th>Currency</th>
<th>Price</th>
<th>Link</th>
<th>City</th>
<th>Country Code</th>
<th>Star Rating</th>
</tr>
<tr class="first">
<td class="from"></td>
<td class="to"></td>
<td class="nights"></td>
<td class="currency"></td>
<td class="price"></td>
<td class="link"></td>
<td class="city"></td>
<td class="country"></td>
<td class="stars"></td>
</tr>
</table>
Javascript -
success : function(parsed_json) {
$.each(parsed_json.Result, function( index, record ) {
$row = $('.first').clone();
var from = record['StartDate'];
$row.find('.from').html(from);
//Similarly repeat the above two lines for other columns
//...
$('#t').append($row);
});
}
I'm trying to display a dynamic running total on a page. I can fill out the fields, click the add button and it adds it to the page with the correct running total. I add a second and third item. The running total again is updating correctly however all running totals for each line are displaying the total running total. How can I fix this?
ListCtrl
angular.module('MoneybooksApp')
.controller('ListCtrl', function ($scope) {
$scope.transactions = [];
$scope.addToStack = function() {
$scope.transactions.push({
amount: $scope.amount,
description: $scope.description,
datetime: $scope.datetime
});
$scope.amount = '';
$scope.description = '';
$scope.datetime = '';
};
$scope.getRunningTotal = function(index) {
console.log(index);
var runningTotal = 0;
var selectedTransactions = $scope.transactions.slice(0, index);
angular.forEach($scope.transactions, function(transaction, index){
runningTotal += transaction.amount;
});
return runningTotal;
};
});
HTML
<div ng:controller="ListCtrl">
<table class="table">
<thead>
<tr>
<th></th>
<th>Amount</th>
<th>Description</th>
<th>Datetime</th>
<th></th>
</tr>
<tr>
<td><button class="btn" ng:click="addToStack()"><i class="icon-plus"></i></button></td>
<td><input type="number" name="amount" ng:model="amount" placeholder="$000.00" /></td>
<td><input name="description" ng:model="description" /></td>
<td><input name="datetime" ng:model="datetime" /></td>
<td></td>
</tr>
<tr>
<th>Running Total</th>
<th>Amount</th>
<th>Description</th>
<th>Datetime</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng:repeat="transaction in transactions" class="{{transaction.type}}">
<td>{{getRunningTotal($index)}} {{$index}}</td>
<td>{{transaction.amount}}</td>
<td>{{transaction.description}}</td>
<td>{{transaction.datetime}}</td>
<td><button class="btn"><i class="icon-remove"></i></button></td>
</tr>
</tbody>
</table>
</div>
You are not using your variable selectedTransactions in your foreach loop. Your foreach loop is calculating all transactions in $scope.transactions.
$scope.getRunningTotal = function(index) {
console.log(index);
var runningTotal = 0;
var selectedTransactions = $scope.transactions.slice(0, index);
angular.forEach($scope.transactions, function(transaction, index){
runningTotal += transaction.amount;
});
return runningTotal;
};
SNIP:
angular.forEach(selectedTransactions, function(transaction, index){
runningTotal += transaction.amount;
});