Cart calculations in AngularJS - angularjs

I'm just starting out with AngularJS attempting to build a shopping cart.
Below is my code.
Items.html
<li id="{{item.id}}" ng-click="addItem(item)" class="menu-item" ng-repeat="item in items">
<span class="list-item-inner">
<span class="item-content">
<span class="vc-outer">
<span class="vc-inner">
<span class="list-item-title" style="color: #3F4B56; font-size: 1.1rem;"
ng-bind="item.name">
</span>
<span class="list-item-description" style="font-size: 0.9rem; color: #6B7781;" ng-bind="item.description">
</span>
</span>
</span>
</span>
</span>
<span class="item-price">
<span class="vc-outer">
<span class="vc-inner no-wrap"
ng-bind="'₦' + (item.price)"></span>
</span>
</span>
<span class="item-add"></span>
</li>
Cart.html
<li class="has-counter order-item" ng-class="{'has-modifier' : cart.length}" ng-repeat="item in cart">
<div class="counter-control-vertical is-editable">
<div class="controls"> <a href="" class="control ctrl-up" ng-click="incQty(item)" style="text-decoration: none;">
+
</a>
<a href="" class="control ctrl-down" ng-click="decQty(item)" style="text-decoration: none;">
–
</a>
</div>
</div>
<div class="oi-inner">
<div class="oi-details" ng-click="editModifiers(item)">
<div class="oi-quantity" ng-bind="(item.count) +'x'"></div>
<div class="oi-title" ng-bind="item.name"></div>
<div class="oi-modifiers"></div>
</div>
<div class="oi-price" ng-bind="'₦' + (item.price)"></div> ×
</div>
</li>
Cart.js
// Array containing my items.
$scope.itemData = <? php echo json_encode($item_array); ?> ;
$scope.cart = [];
$scope.deleteItem = function (item) {
var cart = $scope.cart;
var match = getMatchedCartItem(item);
if (match.count > 0) {
cart.splice(cart.indexOf(item));
return;
}
}
$scope.addItem = function (item) {
var match = getMatchedCartItem(item);
if (match) {
match.count += 1;
return;
}
var itemToAdd = angular.copy(item);
itemToAdd.count = 1;
$scope.cart.push(itemToAdd);
}
$scope.incQty = function (item) {
var match = getMatchedCartItem(item);
if (match) {
match.count += 1;
return;
}
}
$scope.decQty = function (item) {
var cart = $scope.cart;
var match = getMatchedCartItem(item);
if (match.count > 1) {
match.count -= 1;
return;
}
cart.splice(cart.indexOf(item), 1);
}
At the moment I can add, remove, increment and decrement items in the cart array and display them in realtime. But the price does not change based on qty.
My question is;
How can I calculate and display price based on qty of an item in cart?
How do I calculate total price of all the items in the cart array?

ng-bind="item.price * item.count"
I would call a function (witch calculates the total price) every time you change the cart and store the result in an new variable.
$scope.calcTotal = function() {
var total=0;
for (var i = 0, max = $scope.cart.length; i < max; i++) {
total += $scope.cart[i].price * $scope.cart[i].count;
}
$scope.total = total;
}

Related

Firebase Call to the dynamic Reference not giving proper output

i am creating a chat application for the browser using angular 1 and ionic 1
here is my controller and view for that
the problem is when the new message comes in the selected room which is current room watch variable and below console giving me proper output but that same method getting called twice giving me proper output at fist call but after that he gives me main node output.
$scope.firstLoad='';
$scope.directLoad='';
$scope.text = "Tap on name to open chat !";
$scope.myUid = localStorage.uid;
$scope.rooms = [];
$scope.roomsfound = 0;
$scope.roomswait = 1;
$scope.name = "";
$scope.number = "";
$scope.currentRoomId="";
$scope.is_select_user = 0;
$scope.loadDetails = function (roomId, contactName, phone, name) {
$timeout(function () {
$scope.firstLoad=false;
},2000);
$rootScope.showLoading("loadchat");
$scope.currentRoomId="";
$scope.name = "";
$scope.number = "";
$scope.name = name;
$scope.number = phone[0] == '1' ? phone.slice(1) : phone;/*to stipe out 1 from the phone number in view*/
$scope.is_select_user = 1;
$scope.roomName = "Chat";
$scope.chats = [];
$scope.chats.length = 0;
$scope.roomId = '';
$scope.roomId = roomId;
$scope.roomName = contactName;
firebase.database().ref('messages/' + $scope.roomId).once('value', function (data) {
$timeout(function () {
var tempArr = [];
data.forEach(function (data) {
tempArr.push({
key: data.key,
content: data.val().message,
createdAt: data.val().timestamp,
from: data.val().sendBy,
to: data.val().sentTo,
direction: data.val().direction,
status: data.val().status,
type: data.val().type
})
});
$scope.chats = tempArr;
});
});
$scope.currentRoomId= $scope.roomId;
console.log("In Load Details "+$scope.currentRoomId);
if($scope.firstLoad == false){
firebase.database().ref('rooms/' + $scope.myUid +'/'+$scope.roomId ).update({
isRead:'true'
})
}
$scope.Scroll_top();
$rootScope.hideLoading("loadchat");
}
/*Live Chat Listner for Current Room*/
$scope.$watch(
"currentRoomId",
function handleMessageChange( newValue, oldValue ) {
$timeout(function () {
firebase.database().ref('messages/'+$scope.currentRoomId+'/').on('value', function (data) {
console.log('messages/'+$scope.currentRoomId);
if($scope.currentRoomId != ""){
var liveChatArr = [];
$scope.chats = [];
data.forEach(function (data) {
liveChatArr.push({
key: data.key,
content: data.val().message,
createdAt: data.val().timestamp,
from: data.val().sendBy,
to: data.val().sentTo,
direction: data.val().direction,
status: data.val().status,
type: data.val().type
})
});
$scope.chats = [];
$scope.chats.length=0;
if( $scope.chats.length == 0)
$scope.chats=liveChatArr ;
else{
$scope.chats = [];
$scope.chats.length=0;
$scope.chats=liveChatArr ;
}
$scope.Scroll_top();
}
});
},3000);
});
/*End Live Chat Listener*/
/*Send New Message*/
$scope.data = {};
$scope.sendMessage = function (roomId, message, name, phone, contactName) {
Chats.send(roomId, $scope.myUid, message);
document.getElementById("mymsg").value = "";
$scope.data.message='';
};
/* End Send New Message*/
/* Live Room Listner*/
firebase.database().ref('rooms/' + $scope.myUid).orderByChild('lastMessageAt').on('value', function (data) {
$scope.liverooms = [];
$scope.liverooms.length = 0;
$scope.rooms = [];
$scope.rooms.length=0;
$timeout(function () {
var unique = function(origArr) {
//console.log(origArr);
var newArr = [];
var origLen = origArr.length;
var found, x, y;
for (x = 0; x < origLen; x++) {
//console.log(x);
found = undefined;
for (y = 0; y < newArr.length; y++) {
if (origArr[x] === newArr[y]) {
found = true;
break;
}
}
if (!found) {
newArr.push(origArr[x]);
}
}
return newArr;
}
data.forEach(function (data) {
var ref=firebase.database().ref('rooms/' + $scope.myUid);
var key = data.ref.key;
var fields = key.split('_');
var len = fields.length;
var mobile = fields[len - 1];
$scope.liverooms.push({
roomId: key,
contactName: data.val().contactName,
contactfName: (data.val().contactName.split(' '))[0],
lastMessage: data.val().lastMessage,
lastMessageAt: data.val().lastMessageAt,
lastMessageDirection: data.val().lastMessageDirection,
phone: mobile[0] == '1' ? mobile.slice(1) : mobile,
isRead:data.val().isRead
});
});
$scope.rooms = [];
$scope.rooms.length=0;
if( $scope.rooms.length == 0 ){
$scope.rooms=unique($scope.liverooms).reverse();
}else{
$scope.rooms = [];
$scope.rooms.length=0;
$scope.rooms=unique($scope.liverooms).reverse();
}
//console.log($scope.rooms);
});
$scope.roomswait = 0;
if ($scope.rooms.length > 0) {
$scope.roomsfound = 1;
}
});
/* End Live Room Listner*/
VIEW
<div class="content-wrapper">
<div class="container-fluid">
<div class="col-lg-3 searchmain-box">
<br>
<div class="input-group col-sm-6 col-xs-3 col-md-12 mb-2 mr-sm-2 mb-sm-0">
<div class="input-group-addon radius-left search-box"><i class="fa fa-search"></i></div>
<input type="text" class="form-control radius-right search-box" ng-model="search" id="inlineFormInputGroup" placeholder="Search">
</div>
<br>
<div class="col-md-12 text-center" ng-show="roomswait == 1">
<img src="img/loading.gif" width="30">
<br>
<h5 class="text-white">Please Wait.. Loading Chats</h5>
</div>
<ul class="list-group user-list" ng-show="roomsfound == 0">
<li class="list-group-item user-list" style="cursor:pointer;outline:none" ng-if="room" ng-repeat="room in rooms| filter:search " ng-init="($first && firstLoad) ? loadDetails(room.roomId, room.contactName + ' (' + room.phone + ')', room.phone, room.contactName) : ''" type="item-text-wrap" ng-click="loadDetails(room.roomId, room.contactName + ' (' + room.phone + ')', room.phone, room.contactName)">
<!--<li class="list-group-item user-list" ng-repeat="room in rooms| orderBy:'lastMessageAt':true | filter:search" type="item-text-wrap" ng-click="loadDetails(room.roomId, room.contactName + ' (' + room.phone + ')', room.phone, room.contactName)">-->
<div class="user-profile" ng-if="room.contactName == name && room.phone == number">
<span><img src="img/liveicon.png"></span>
</div>
<div class="user-name" >
<h4 class="ma-0" ng-class="{'user-live':room.contactName == name && room.phone == number , 'dark-text':(room.contactName != name || room.phone != number) && room.isRead != 'false' , 'not_read':room.isRead == 'false'}" >
{{room.contactName}}
<span class="live-chaticon"></span>
</h4>
<span style="float:left"><img src="img/phone.png"/></span>
<p class="user-phoneno mb-0" style="padding:5px;margin-left: 16px;" ng-class="{'not_read':room.isRead == 'false'}">
{{room.phone| bcTelephone:'format'}}
</p>
<p class="user-message mb-0" style="font-size: 12px;" ng-show="room.lastMsg != ''" ng-class="{'not_read':room.isRead == 'false', 'dark-text':room.isRead == 'true'}">
<span ng-if="room.lastMessageDirection == 'out'">You:</span>
<span ng-if="room.lastMessageDirection == 'in'">{{room.contactfName}}:</span>
{{(room.lastMessage| limitTo: 20) + (room.lastMessage.length > 20 ? '..' : '')}}
</p>
</div>
<div class="user-time">
<p class="dark-text">
<span class="time2" ng-show="room.lastMessageAt != ''" am-time-ago="room.lastMessageAt"></span>
</p>
</div>
</li>
</ul>
</div>
<div class="recent-bg" block-ui="loadchat" style="width:61%;position:fixed;top:0;right:0;background-color:white">
<div class="recent-order">
<!-- <div class="recent-text ">
<h4 class="user-name">{{name}} <span class="live-chaticon"></span></h4>
<h5> <span style="float:left"><img src="img/phone.png" height="20px"/></span> {{number| bcTelephone:'format'}} </h5>
</div>-->
<div class="recent-text ">
<div class="row">
<div class="col-md-3">
<h4 class="user-name">{{name}} <span class="live-chaticon"></span></h4>
<!--<h5 class="user-number">{{number}} </h5>-->
<!--<h5 class="user-number"> {{number| bcTelephone:'format'}} </h5>-->
<h5> <span style="float:left"><img src="img/phone.png" height="20px"/></span> {{number| bcTelephone:'format'}} </h5>
</div>
</div>
</div>
</div>
<div class="col-12 pa-0">
<h5 ng-if="text != ''" class="text-center">{{text}}</h5>
<div class="table-responsive">
<div class="frame">
<div ng-show="chats.length != 0">
<ul class="message-box">
<li ng-repeat="chat in chats| orderBy:'createdAt':false" ng-if="chat" ng-class="{'pull-right default-user ': chat.direction == 'out','pull-left client-user':chat.direction != 'out'}">
<p>{{chat.content}} <br>
<span style="font-size: 10px;" am-time-ago="chat.createdAt" ng-class="{'pull-right default-user': chat.direction == 'out','pull-left client-user':chat.direction != 'out'}"></span>
<br>
<span style="font-size: 10px; float: right" > {{chat.status}}</span>
</p>
</li>
</ul>
</div>
<div class="message-sendbtn" style="position:fixed;width:61%" ng-show="is_select_user">
<div class="input-group">
<input type="text" class="form-control message-control" id="mymsg" placeholder="Your message" ng-model="data.message" aria-label="Recipient's username" aria-describedby="basic-addon2" ng-enter="sendMessage(roomId, data.message, name, number, roomName)">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
This is My View
I am getting issue when new message comes in node Contact list which is Room array getting double records and when i send message some time its not showing live status of message and some time it messes up with wrong node (Current Room)
By using on("value") method is getting called multiple times.
Kindly help me i am stuck here.

ng-show is not working with ng-repeat

Below is my table markup
<tr ng-show="paginate({{$index+1}})" ng-repeat="x in ProductInfo_Pager | orderBy :sortType:sortReverse | filter:searchText | limitTo : rowPerPage" ng-class="$even?'table-danger':'table-info'">
<td>{{$index+1}}</td>
<td>{{x.Product}}</td>
<td>{{x.Location}}</td>
<td>{{x.Qty}}</td>
<td>{{x.UnitPrice | currency : '₹':2}}</td>
<td class="text-center">
<i class="fa fa-flag" aria-hidden="true" style="color:red" /> |
<i class="fa fa-bolt" aria-hidden="true" style="color:red" /> |
<i class="fa fa-users" aria-hidden="true"></i>
</td>
</tr>
and pager below it
<ul class="pagination">
<li class="page-item" ng-repeat="x in getNumber(rowPerPage) track by $index">
<a class="page-link" ng-click="pagerIndex=$index+1">{{$index+1}}</a>
</li>
</ul>
And AngularJs Code
$scope.ProductInfo_Pager = $scope.ProductInfo;
$scope.sortType = 'Product'; // set the default sort type
$scope.sortReverse = false; // set the default sort order
$scope.searchText = ''; // set the default search/filter term ,
$scope.totalItems = $scope.ProductInfo.length;
$scope.currentPage = 1;
$scope.rowPerPage = 5;
$scope.pagerIndex = 1;
$scope.getNumber = function (num) {
var pages = $window.Math.ceil($scope.totalItems / num);
return new Array(pages);
}
$scope.paginate = function (rowindex) {
var begin, end, index, flag ;
index = $scope.pagerIndex;
end = (index * $scope.rowPerPage) - 1; // -1 to sync it with zero based index
begin = end - $scope.rowPerPage + 1;
if(rowindex >=begin && rowindex <= end ){
flag=true;
}
else{
flag=false;
}
var d = 0;
return flag;
};
paginate function() return true or false based on logic which is used in ng-show in tr tag with ng-repeat, but its not doing show , hide functionality as expected
Logic is :
Suppose rowPerPage is 5 - [5 row can be show up in table at a time]
And we click on 4 in pager so it should show row from 16-20 .
In ng-show paginate function is bind which take row index as parameter , this function check if rowindex falls in between 16 - 20 , if yes than it return true (ng-show=true) else false and accordingly should hide that row.
As per mu understanding its two way binding so any change in ng-show should work perfectly but it does not show any effect
Can someone help me why this is happening
I am a newbie in angularjs
Thanks.
Well ! ng-show is not working here and the function is not getting called at all written in ng-show !
If i correctly understand you want to create a pagination :
So i am giving you a very simple solution of pagination using a pagination filter .
you need to add this filter to your app :
app.filter('pagination', function() {
return function(input, start) {
start = +start; //parse to int
if (input != undefined && Object.keys(input).length > 0) {
return input.slice(start);
}
}
});
In your html :
<tr ng-repeat="x in ProductInfo_Pager | pagination: currentPage * rowPerPage | limitTo: rowPerPage|orderBy :sortType:sortReverse | filter:searchText" ng-class="$even?'table-danger':'table-info'">
<td>{{$index+1}}</td>
<td>{{x.Product}}</td>
<td>{{x.Location}}</td>
<td>{{x.Qty}}</td>
<td>{{x.UnitPrice | currency : '₹':2}}</td>
<td class="text-center">
<i class="fa fa-flag" aria-hidden="true" style="color:red" /> |
<i class="fa fa-bolt" aria-hidden="true" style="color:red" /> |
<i class="fa fa-users" aria-hidden="true"></i>
</td>
</tr>
In your pagination ul below your table :
<ul class="pagination">
<li class="page-item" ng-repeat="x in getNumber(rowPerPage) track by
$index">
<a class="page-link" ng-click="pagerIndex=$index+1">{{$index+1}}
</a>
</li>
</ul>
in your controller :
$scope.numberOfPages = function() {
if ($scope.ProductInfo_Pager != undefined) {
return Math.ceil($scope.ProductInfo_Pager.length /
$scope.rowPerPage);
}
};
Hope it work ! if any doubt please let me know .

ng-repeat shows another ng-repeat data

Hi i am trying to show up 2 menu's
Deparments -> subdepartments
List item
onclick of "event" button
should show up. onclick of "dates", button
should show up.
Here the issue is both the 1) and 2) display in single menu though both the htmls are different. Where am i going wrong.Below is the code.
HTML:
<div class="tab" >
<div class="sidebar-top">
<ul class="nav nav-pills nav-justified">
<li class="active">Event</li>
<li>Date</li>
</ul>
</div>
<div class="tab-content clearfix">
<div class="tab-pane active" id="1a">
<ul class="nav nav-sidebar">
<li class=" nav-active active"><i class="icon-home"></i><span>Dashboard</span></li>
<li class="nav-parent" ng-repeat="(key, value) in getdatewasedetails | groupBy: 'depatName'">
<i class="fa fa-link"></i><span></span>{{ key }} <span class="fa arrow"></span>
<ul class="children collapse" ng-repeat="subdept in value">
<li > {{ subdept.serviceName }} </li>
</ul>
</li>
</ul>
</div>
<div class="tab-pane" id="2a">
<ul class="nav nav-sidebar">
<li class=" nav-active active"><i class="icon-home"></i><span>Dashboard</span></li>
<li class="nav-parent" ng-repeat="(key, value) in getdatewasedetails| groupBy: 'month'">
<i class="fa fa-link"></i><span></span>{{ key | date:'MMMM' : 'UTC' }} <span class="fa arrow"></span>
<ul class="children collapse" ng-repeat="currDates in value">
<li > {{currDates.testDate | date:'longDate' : 'UTC'}} </li>
</ul>
</li>
</ul>
</div>
</div>
</div>
Resulted Json:
Angular JS:
$scope.lastVisit = function () {
var request = $http({
method: "get",
url: "dashboardServiceCall.php",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP get request or not */
request.success(function (data, status, headers, config) {
z=0;
for(var x=0; x < data.length; x++){
if(data[x]['type'] == 3){
for(var g=0; g<data[x]['data']['dateWaseReportResForTests'].length; g++){
$scope.getdatewasedetails[z] = data[x]['data']['dateWaseReportResForTests'][g];
$scope.getdatewasedetails[z].testDate = new Date($scope.getdatewasedetails[z].testDate);
$scope.getdatewasedetails[z].category = data[x]['data']['panelName'];
$scope.getdatewasedetails[z].month = $scope.getdatewasedetails[z].testDate.getMonth();
z++;
}
for(var y=0; y<data[x]['data']['dateWaseReportResForGroups'].length; y++){
for(var d=0; d< data[x]['data']['dateWaseReportResForGroups'][y]['data']['dateWaseReportResForTests'].length; d++){
$scope.getdatewasedetails[z] = data[x]['data']['dateWaseReportResForGroups'][y]['data']['dateWaseReportResForTests'][d];
$scope.getdatewasedetails[z].testDate = new Date($scope.getdatewasedetails[z].testDate);
$scope.getdatewasedetails[z].category = data[x]['data']['panelName'];
$scope.getdatewasedetails[z].month = $scope.getdatewasedetails[z].testDate.getMonth();
z++;
}
}
}else if(data[x]['type'] == 1 ){
for(var g=0; g<data[x]['data']['dateWaseReportResForTests'].length; g++){
$scope.getdatewasedetails[z] = data[x]['data']['dateWaseReportResForTests'][g];
$scope.getdatewasedetails[z].testDate = new Date($scope.getdatewasedetails[z].testDate);
$scope.getdatewasedetails[z].category = data[x]['data']['dateWaseReportResForTests'][g]['serviceName'];
$scope.getdatewasedetails[z].month = $scope.getdatewasedetails[z].testDate.getMonth();
z++;
}
}else if(data[x]['type'] == 2){
for(var y=0; y<data[x]['data']['dateWaseReportResForGroups'].length; y++){
for(var d=0; d< data[x]['data']['dateWaseReportResForGroups'][y]['data']['dateWaseReportResForTests'].length; d++){
$scope.getdatewasedetails[z] = data[x]['data']['dateWaseReportResForGroups'][y]['data']['dateWaseReportResForTests'][d];
$scope.getdatewasedetails[z].testDate = new Date($scope.getdatewasedetails[z].testDate);
$scope.getdatewasedetails[z].category = data[x]['data']['dateWaseReportResForGroups'][y]['data']['groupName'];
$scope.getdatewasedetails[z].month = $scope.getdatewasedetails[z].testDate.getMonth();
z++;
}
}
}
}
$scope.leftNavMenu = $scope.getdatewasedetails;
});
}
Above two images show output.both the ng-repeats are rendering. i am not sure where am i going wrong.Any help would be great. thanks in advance.

when ng-repeat list of folders updates wrong

I have receive listof objects with names: F1,F2,F3,F4
when I make call to server, I receive new list F1,F2,F3,F5,F4
when I apdate ng-repeat list:
vm.folders = data.content.items;
it shows next list: F1,F2,F3,F4,F4
where am I wrong? here is my html code:
<div ng-repeat="folder in vm.folders track by $index" ng-init="openInput=false;">
<div layout="row" ng-init="folderName = vm.getIterationName(folder.metadata)" >
<div >
</div>
<div >
<span ng-click="showChildren[$index]=!showChildren[$index]" class="capitalize" ng-dblclick="openInput = true;$event.stopPropagation();" ng-show="!openInput">{{folderName}}</span>
</div>
</div>
</div>
js update method:
function updateIterations(data) {
if (data.ok === true) {
if(angular.toJson(vm.folders) != angular.toJson(data.content.items)) {
vm.folders = data.content.items;
}
} else if (data.ok == false) {
console.log ('Error:iteration request: {ok: false}');
$interval.cancel(intervalRequests);
}
}
fixed!
in
<span ng-click="showChildren[$index]=!showChildren[$index]" class="capitalize" ng-dblclick="openInput = true;$event.stopPropagation();" ng-show="!openInput">{{folderName}}</span>
instead of {{folderName}} i've used:
<span ng-click="showChildren[$index]=!showChildren[$index]" class="capitalize" ng-dblclick="openInput = true;$event.stopPropagation();" ng-show="!openInput">{{vm.getIterationName(folder.metadata)}}</span>

anguarljs, ng-repeat, how can i assign the output of the function to a variable and use this variable in the current loop

I have the following data:
$scope.AcctHistList = "[{"AcctHistID":13,"AcctID":6,"TranAmount":444,"TranDSC":"IncomeBill","UserDSC":"423142341","TXID":"ec9a8fb7-9f76-4671-f7c7-75a77c2a7a04","Created_D":"2015-09-14","Created_T":"08:00","Created_DT":"2015-09-14 08:00","Created_YM":"2015-09","Created_W":"37","Created_Y":"2015","Created_w":"Mo","AcctCurrency":"AED"}
,{"AcctHistID":12,"AcctID":6,"TranAmount":444,"TranDSC":"IncomeBill","UserDSC":"undefined","TXID":"eaec26e6-4dc1-41a3-e987-d27843cefed8","Created_D":"2015-09-14","Created_T":"08:00","Created_DT":"2015-09-14 08:00","Created_YM":"2015-09","Created_W":"37","Created_Y":"2015","Created_w":"Mo","AcctCurrency":"AED"}
,{"AcctHistID":11,"AcctID":6,"TranAmount":444,"TranDSC":"IncomeBill","UserDSC":"undefined","TXID":"16a323b3-0f11-4a18-e753-e4f262ace2ca","Created_D":"2015-09-14","Created_T":"08:00","Created_DT":"2015-09-14 08:00","Created_YM":"2015-09","Created_W":"37","Created_Y":"2015","Created_w":"Mo","AcctCurrency":"AED"}
,{"AcctHistID":10,"AcctID":6,"TranAmount":44,"TranDSC":"IncomeBill","UserDSC":"423141234","TXID":"bc5b4a80-0322-4e04-9bb4-5a82973c99a7","Created_D":"2015-10-11","Created_T":"09:12","Created_DT":"2015-10-11 09:12","Created_YM":"2015-10","Created_W":"40","Created_Y":"2015","Created_w":"Su","AcctCurrency":"AED"}
,{"AcctHistID":9,"AcctID":6,"TranAmount":44,"TranDSC":"IncomeBill","UserDSC":"423141234","TXID":"e8ba0ec2-e007-4925-94af-7cc038937aa3","Created_D":"2015-10-11","Created_T":"09:12","Created_DT":"2015-10-11 09:12","Created_YM":"2015-10","Created_W":"40","Created_Y":"2015","Created_w":"Su","AcctCurrency":"AED"}
,{"AcctHistID":8,"AcctID":6,"TranAmount":44,"TranDSC":"IncomeBill","UserDSC":"423141234","TXID":"d516756f-afc6-454b-c7d1-db55c474397f","Created_D":"2015-10-11","Created_T":"09:12","Created_DT":"2015-10-11 09:12","Created_YM":"2015-10","Created_W":"40","Created_Y":"2015","Created_w":"Su","AcctCurrency":"AED"}
]"
in the view i iterate through these data and group it using the user input(Day,Month,Week,Year,...).
<div class="panel panel-info" ng-repeat="group in AcctHistList | groupBy:AcctHistGropuBy | toArray:true | orderBy:'-$key'">
<div class="panel-heading">
<strong data-i18n={{group.$key}}>{{group.$key}}</strong>
<span class="label pull-right" ng-model="SumAmount = SumTranAmount(group)">
<span class="badge">{{SumAmount.In}}</span>
<span class="badge">-{{SumAmount.Out}}</span>
<span class="badge">={{SumAmount.Total}}{{SumAmount.Currency}}</span>
</span>
</div>
<div class="panel-body">
<ul class="list-group" ng-repeat="item in group">
<li class="list-group-item">
<h4 class="list-group-item-heading" data-i18n={{item.TranDSC}}>
{{item.TranDSC}}
</h4>
<span class="badge">{{item.Created_DT}}</span>
<span class="badge">{{item.TranAmount}} {{item.AcctCurrency}}</span>
<p class="list-group-item-text">{{item.UserDSC}}</p>
</li>
</ul>
</div>
The main problem is that, i want to summarize each group (to calculate TotalIn, TotalOut, and In-Out), So i wrote the function SumTranAmount for this.
$scope.SumTranAmount = function (group) {
var Total = 0, In = 0, Out = 0;
for (var i = 0; i < group.length; i++) {
Total = Total + group[i].TranAmount
if (group[i].TranAmount >= 0) {
In = In + group[i].TranAmount;
}
else {
Out = Out - group[i].TranAmount;
}
}
//return (In + " " + Out + " = " + Total + " " + group[0].AcctCurrency);
return { In: In, Out: Out, Total: Total, Currency: group[0].AcctCurrency };
}
Problem, an exception occured ng-model="SumAmount = SumTranAmount(group)"
So, my question is, how can i assign the output of the function to a variable and use this variable in the current loop??

Resources