How to detect where recursive functions are called - javascript

while trying to implement a cart for my eshop I have noticed that initCartId and refreshCart are called recursively, causing the project to crash.
The problem is the same with this one but this cannot help me to identify where I use recursion.
The alerts from controller.js when I go to cart page are:
initCartId!!!
refreshCart!!!
calGrandTotal!!!
calGrandTotal!!!
calGrandTotal!!!
The first 2 alerts from calGrandTotal function looks like:
At this point I can see the StackOverFlowError at the console but the alerts continue to appear one more time with the following sequence:
initCartId!!!
refreshCart!!!
calGrandTotal!!!
cart.jsp
<%#taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%#include file="/WEB-INF/views/template/header.jsp"%>
<div class="container-wrapper">
<div class="container">
<section>
<div class="jumbotron">
<div class="container">
<h1>Cart</h1>
<p>All the selected products in your shopping cart</p>
</div>
</div>
</section>
<section class="container" ng-app="cartApp">
<div ng-controller="cartCtrl" ng-init="initCartId('${cartId}')">
<div>
<a class="btn btn-danger pull-left" ng-click="clearCart()"><span
class="glyphicon glyphicon-remove-sign"></span>Clear Cart</a>
</div>
<table class="table table-hover">
<tr>
<th>Product</th>
<th>Unit Price</th>
<th>Quantity</th>
<th>Price</th>
<th>Action</th>
</tr>
<tr ng-repeat="item in cart.cartItems">
<td>{{item.product.productName}}</td>
<td>{{item.product.productPrice}}</td>
<td>{{item.quantity}}</td>
<td>{{item.totalPrice}}</td>
<td><a href="#" class="label label-danger"
ng-click="removeFromCart(item.product.productId)"> <span
class="glyphicon glyphicon-remove"></span>remove
</a></td>
</tr>
<!-- <tr>
<th></th>
<th></th>
<th>Grand Total</th>
<th>{{calGrandTotal()}}</th>
<th></th>
</tr> -->
</table>
<a href="<spring:url value="/productList" />"
class="btn btn-default">Continue Shopping</a>
</div>
</section>
</div>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<script src="<c:url value="/resources/js/controller.js" /> "></script>
<%#include file="/WEB-INF/views/template/footer.jsp"%>
controller.js
var cartApp = angular.module ("cartApp", []);
cartApp.controller("cartCtrl", function ($scope, $http){
/* corresponding to the mapper at CartController with RequestMethod.GET */
/*
* /eMusicStore/rest/cart/'+$scope.cartId) get the cart data in Json format
* and with the success we use another function and the JSON format cart
* info will be stored into data and we pass into $scope
*/
$scope.refreshCart = function (cartId) {
alert("refreshCart!!!");
$http.get('/eMusicStore/rest/cart/'+$scope.cartId).success(function (data) {
$scope.cart=data;
});
};
$scope.clearCart = function () {
alert("clearCart!!!");
/*$http.delete('/eMusicStore/rest/cart/'+$scope.cartId).success($scope.refreshCart($scope.cartId));*/
$http.delete('/eMusicStore/rest/cart/'+$scope.cartId).success(function (data) {
$scope.refreshCart($scope.cartId);
});
};
$scope.initCartId = function (cartId) {
alert("initCartId!!!");
$scope.cartId = cartId;
/* alert("cartId:" + cartId);*/
$scope.refreshCart($scope.cartId);
};
$scope.addToCart = function (productId) {
alert("addToCart!!!");
$http.put('/eMusicStore/rest/cart/add/'+productId).success(function (data) {
/*$scope.refreshCart($http.get('/eMusicStore/rest/cart/cartId'));*/
alert("Product successfully added to the cart!");
});
};
$scope.removeFromCart = function (productId) {
alert("removeFromCart!!!");
$http.put('/eMusicStore/rest/cart/remove/'+productId).success(function (data) {
/*$scope.refreshCart($http.get('/eMusicStore/rest/cart/cartId'));*/
$scope.refreshCart($scope.cartId);
});
};
$scope.calGrandTotal = function () {
alert("calGrandTotal!!!");
var grandTotal=0;
for (var i=0; i<$scope.cart.cartItems.length; i++) {
grandTotal+=$scope.cart.cartItems[i].totalPrice;
}
return grandTotal;
};
});

Related

How to display data using DataTable fetched data from API?

I have data fetched form API. I want to display it into the DataTable.
The data is fetched from the API and it got displayed into the DataTable but I have problem in displaying the data. The data is displayed but it also give me
No data available in table
below is what I have tried
<div class="nk-block nk-block-lg">
<div class="nk-block-head">
<div class="nk-block-head-content">
<h4 class="nk-block-title">Data </h4>
<div class="nk-block-des">
<p>Policy</p>
</div>
</div>
</div>
<div class="card card-preview">
<div class="card-inner">
<table class="datatable-init table" id="datatable">
<thead>
<tr>
<th>#</th>
<th>Module</th>
<th>Policy & Terms of Services Details</th>
</tr>
</thead>
<tbody id="dataDetails">
</tbody>
</table>
</div>
</div>
<!-- .card-preview -->
</div>
<!-- nk-block -->
< script >
let cnt = 1;
$(document).ready(function() {
getList();
})
const getList = () => {
axios.get(`${url}getList`)
.then(function(res) {
if (res.data.status == 'success') {
res.data.result.map((e) => {
if (e.role_id == '3') {
$("#dataDetails").append(`
<tr>
<td>${cnt++}</td>
<td>${e.name}</td>
<td>${e.title}</td>
</tr>
`
);
}
})
}
})
}
<
/script>
How do I fix the problem ? Because inside the table have data, but it keep displaying the No data available in table
after adding the $("#datatable").DataTable(); inside the const
$("#dataDetails").append(`
<tr>
<td>${cnt++}</td>
<td>${e.name}</td>
<td>${e.title}</td>
</tr>
`
$("#datatable").DataTable();
);
I got error with Uncaught SyntaxError: missing ) after argument list
showing at this line

Issue with removing displayed list of items

I am creating a restaurant menu app that a waiter can use to input orders.
I have everything set to where when I select an food item button. That item is added to a list of chosen items for purchase in a list displayed on screen.
I have remove buttons next to each item in case you want to remove one. The remove button works, however it always removes the first item from the list and not the item that had it's particular remove button selected.
I'm not sure why it is doing this. What could I do to get the current item removed that had it's particular remove button selected?
Js code
.controller('orderAddCtrl', ['$scope', '$location', 'dataService', function ($scope, $location, dataService) {
$scope.chosenItems = [];
$scope.totalItemPrices = 0;
$scope.userId = "";
$scope.addOrderToList = function (item) {
$scope.addPricesToTotalItemPrices(item.itemPrice);
$scope.chosenItems.push({'Name': item.itemName, 'Price': item.itemPrice});
};
$scope.addPricesToTotalItemPrices = function (price) {
$scope.totalItemPrices += price ;
};
$scope.removePricesFromTotalItemPrices = function (price) {
$scope.totalItemPrices -= price;
};
$scope.removeFromOrderToList = function (item) {
$scope.removePricesFromTotalItemPrices(item.Price);
$scope.chosenItems.splice(item, 1);
};
Html
<div class="row">
<div class="col-6">
<h2>Food Items</h2>
<div class="row">
<button class="btn btn-success col-3" ng-repeat="item in Items" ng-click="addOrderToList(item)">{{item.itemName}}</button>
</div>
</div>
<div class="col-6">
<table class="table table-bordered">
<thead>
<tr>
<th>Item Name</th>
<th>Item Price</th>
<th>Total Price: ${{totalItemPrices}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="i in chosenItems">
<td>{{i.Name}}</td>
<td>{{i.Price}}</td>
<td>
<button class="btn btn-danger" ng-click="removeFromOrderToList(i)">
Remove
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
This is the splice syntax:
array.splice(startindex, howmany, item1, ....., itemX)
https://www.w3schools.com/jsref/jsref_splice.asp
If you pass a string as a parameter where an integer is expected it will, in the case of splice, first attempt to parse the string as an integer.
When the parse returns NaN it will default to 0, which explains the behavior of your code.

How to change Background color of table row based on respective cell data using angularjs?

I want to change Background color of row based on cell data, like if it matches first four characters from table cell "td", then row should change its color to red.
here is my example, it is working but it takes whole cell data.but i want row color should change once it matches first four characters from cell.
<style>
.bgRed{
background-color:red;
}
</style>
<body ng-app="myApp">
<div ng-controller="myController">
<div class="container" style="margin-top:40px;">
<div class="row">
{{error}}
<div class="col-md-6">
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th>Name</th>
<th>Class Name</th>
<th>Roll No</th>
<th>Email</th>
</tr>
</thead>
<tbody ng-repeat="std in students">
**<tr ng-class="{'bgRed': std.Name === 'Prash'}>**
<td>{{std.Name}}</td>
<td>{{std.ClassName}}</td>
<td>{{std.RollNo}}</td>
<td>{{std.Email}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
and my table is
Table row should change to red if table cell data "Prash or Prashant" matches.instead of taking "Prashant Olekar"
how to achive this please help. Thank you
Using substring you can trim the characters of the string,
here I'm creating one more variable(filed) "trimmed_name" which is a substring of your "name" which gives you first 4 characters of your string "name".
<tr ng-repeat="std in students" ng-init="trimName(std)">
<td ng-class="{'bgRed': std.trimmed_name === 'Prash', 'bgBlue': std.trimmed_name === 'Pavi', 'bgBlack' : std.trimmed_name === 'Pava'}">{{std.Name}}</td>
<td>{{std.ClassName}}</td>
<td>{{std.RollNo}}</td>
<td>{{std.Email}}</td>
</tr>
In Css add respective colours for respective classes
in your controller
$scope.trimName = function (std) {
std.trimmed_name = std.Name.substring(0, 4);
return std;
};
Just in case if 'Prash' dose not work use {'bgRed': std.trimmed_name === "Prash"}
Hope it helps you.
you can use a custom filter to set class according to condition of your row data,
html
<tbody ng-repeat="std in students | filter:filterColor">
<tr class="{{std.class}}">
<td>{{std.Name}}</td>
<td>{{std.ClassName}}</td>
<td>{{std.RollNo}}</td>
<td>{{std.Email}}</td>
</tr>
</tbody>
js
$scope.filterColor = function (item) {
if (your condition) {
item.class = 'your class';
}
else
item.class = 'some other class';
return true;
};
I have got solution to my question with the help of Rajat, here is my code. but it only matches characters from 0th Position.
<head>
<title></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/App/app.js"></script>
<style>
.bgRed {
background-color: #cfeaff;
}
</style>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<div class="container" style="margin-top:40px;">
<div class="row">
{{error}}
<div class="col-md-6">
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th>Name</th>
<th>Class Name</th>
<th>Roll No</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="std in students" ng-init="trimName(std)" ng-class="{bgRed: std.trimmed_name === 'Pras'}">
<td>{{std.Name}}</td>
<td>{{std.ClassName}}</td>
<td>{{std.RollNo}}</td>
<td>{{std.Email}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
and In Controller
/// <reference path="../angular.min.js" />
var myApp = angular.module('myApp', [])
.controller("myController", function ($scope, $http, $log) {
var successCallback = function (response) {
$scope.students = response.data;
$log.info(response);
}
var errorCallback = function (response) {
$scope.error = response.data;
$log.info(response);
}
$scope.StudentsData = $http({
method: 'GET',
url: 'PKWebService.asmx/getPkData'
})
.then(successCallback, errorCallback);
$scope.trimName = function (std) {
std.trimmed_name = std.Name.substring(0, 4);
return std;
};
});
and output is
Thank you

how to get all data using select all checkbox in table?

Hi I am trying to get all data at a time when I will click on
checkbox, but data not coming but when i click one by one data id
coming. But my problem is how to get all data in checkbox all in
single click.
This is HTML code
<div id="wrapper" class="wrapper">
<div ng-include="'views/partials/navigator.html'"></div>
<div class="page-content-wrapper">
<div ng-include="'views/partials/header.html'"></div>
<div class="row">
<div class="col-md-12">
<h3>Student Information</h3>
<table id="example" class="table">
<tr>
<th>Name</th>
<th>Mobile</th>
<th>Siblling</th>
<th>select all <input type="checkbox" id="slctAllDuplicateStd"/></th>
</tr>
<tr ng-repeat="data in vm.data">
<td>{{data.name}}</td>
<td>{{data.mobileNumber}}</td>
<td>{{data.isMigrated}}</td>
<td><input type="checkbox" ng-model="data.selected" class="duplicateRow" /></td>
</tr>
<tr>
<tr>
<button class ="button" ng-click="vm.process()">Process</button>
</tr>
</table>
<table class="table">
<tr>
<td colspan="4">
<pagination ng-if="renderpagination" page-number='{{vm.pageNumber}}' page-count="{{vm.pageCount}}" total-records="{{vm.totalRecords}}" api-url="duplicate-student"></pagination>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
This is javascript code
(function() {
angular
.module('vidyartha-coordinator')
.controller('StudentDuplicateAccountController', StudentDuplicateAccountController);
StudentDuplicateAccountController.$inject = ['$scope', 'ApiService', '$routeParams', '$http', '$location', '$timeout'];
function StudentDuplicateAccountController($scope, ApiService, $routeParams, $http, $location, $timeout) {
var vm = this;
//console.log($routeParams)
var page = $routeParams.page || 1;
// vm.data = [];
ApiService.getAll('student-duplicate-account?pageCount=5&pageNumber=' + page).then(function(response) {
//console.log("response::"+JSON.stringify(response));
vm.data = response.data.records;
vm.pageNumber = response.data.pageNumber;
vm.totalRecords = response.data.totalRecords;
vm.pageCount = response.data.pageCount;
$scope.renderpagination = true;
});
$("#slctAllDuplicateStd").click(function () {
$(".duplicateRow").prop('checked', $(this).prop('checked'));
// console.log('data:::'+JSON.stringify(data));
});
vm.process = function() {
vm.duplicateArray = [];
angular.forEach(vm.data, function(data){
if (data.selected) {
console.log("true")
vm.duplicateArray.push(data.tenantId);
vm.duplicateArray.push(data.mobileNumber);
vm.duplicateArray.push(data.schoolId);
vm.duplicateArray.push(data.classId);
}
});
console.log(vm.duplicateArray)
}
}
})();
I need all data at a time we i do check and press process button.
So please tell me where i should add some condition.
Am not sure why you are mixing jquery here you can do it as follow
vm.selectAll =function(){
angular.forEach(vm.data, function(data){
data.selected=true;
}
then in your checkbox
<th>select all <input type="checkbox" ng-click="vm.selectAll()"/></th>

javascript/jquery not working in the partial view.

I have a main view and in it I have a partial view. In my partial view, I have a table which shows some results of a search carried out. what I want is that when I click on the row, it should alert the data in that row. but this is not happening.
I tried nearly everything on the internet but couldn't find anything.
Partial view:
#model List
<string>
<table class="table table-striped" id="tblGrid">
<thead id="tblHead">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
#for (int item = 0; item < Model.Count; item = item + 2)
{
<tr>
<td style="width: 300px">
#Model[item].ToString()
</td>
#{ int temp = item;
item = item + 1;
}
<td style="width: 100px">
#Model[item].ToString()
</td>
#{
item = temp;
}
</tr>
}
</tbody>
</table>
Data is populated just fine, but the javascript is not called.
main:
<head>
<script type="text/javascript">
$(document).ready(function () {
$("#tblGrid tr").live(function () {
$(this).addClass('selected').siblings().removeClass('selected');
var value = $(this).find('td:first').html();
alert(value);
});
});
</script>
</head>
<body>
<input id="searchAttr" name="searchAttr" />
<button href="#myModal" id="openBtn" data-toggle="modal" class="btn btn-default">Search</button>
<div id="searchresults">
</div>
</body>
Any help provided will be appreciated.
place your script tag in body instead of head and then try
Are you trying to use jQuery without connecting your view with it?
Add to the top of of your main this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

Categories