Angularjs - how to update Dropdown depending on other Dropdown in Dynamic table? - javascript

var myAppRxCafe = angular.module('DescRxCafe', []);
myAppRxCafe.controller('RxCafeController', ['$scope', '$http', function($scope, $http) {
$scope.RxItemDetailArray = [];
$http.get("/URL ")
.then(function(response) {
var itemListArray = response.data.records;
for (var i = 0; i != response.data.records.length; i++) {
$scope.RxItemDetailArray.push({
'itemName': itemListArray[i].u_item_name,
'itemPrice': itemListArray[i].u_itemprice_decimal
});
console.log('Data from Server- ' + JSON.stringify(response.data.records));
}
});
$scope.RxCafeObj = [{
'rxCafeReqItem': '',
'rxCafeReqQty': 1,
'rxCafeReqTime': '',
'rxCafeReqOrderNotes': '',
'rxCafeReqPrice': 0,
'rxCafeReqTotalPrice': 0,
}];
$scope.addRow = function() {
$scope.rxCafeReqItem = '';
$scope.rxCafeReqQty = 1;
$scope.rxCafeReqTime = '';
$scope.rxCafeReqOrderNotes = '';
$scope.rxCafeReqPrice = 0;
$scope.rxCafeReqTotalPrice = 0;
$scope.RxCafeObj.push({
'rxCafeReqItem': $scope.rxCafeReqItem,
'rxCafeReqQty': $scope.rxCafeReqQty,
'rxCafeReqTime': $scope.rxCafeReqTime,
'rxCafeReqOrderNotes': $scope.rxCafeReqOrderNotes,
'rxCafeReqPrice': $scope.rxCafeReqPrice,
'rxCafeReqTotalPrice': $scope.rxCafeReqTotalPrice,
});
};
$scope.updatePrice = function(itemSelected) {
$scope.availablePrice = [];
angular.forEach($scope.RxItemDetailArray, function(value) {
if (value.itemName == itemSelected) {
$scope.availablePrice.push(value.itemPrice);
}
});
};
$scope.removeRow = function($index) {
if ($index != 0) {
$scope.RxCafeObj.splice($index, 1);
}
};
}]);
<div ng-app="DescRxCafe" ng-csp="no-unsafe-eval" id="divId2">
<div ng-controller="RxCafeController">
<table style="height: 28px;" width="430" class="table table-bordered" id="dataTable_RxCafeController">
<tbody>
<tr>
<th>Requested Item</th>
<th>Quantity</th>
<th>Time</th>
<th>Order Notes</th>
<th>Price</th>
<th>Total Price(Qty * price * 0.06)</th>
</tr>
<tr ng-repeat="company in RxCafeObj">
<td>
<select class="form-control input1" ng-model="rxItemName" name="rxCafeReqItem" id="selectedElectronicRec" ng-change="updatePrice(rxItemName)">
<option value='none_RxCafeController_input'>None</option>
<option ng-repeat="v in RxItemDetailArray | orderBy:'itemName':false" value="{{v.itemName}}">{{v.itemName}}</option>
</select>
</td>
<td>
<input type="number" class="form-control input1" id="RxCafeController_input" ng-model="rxQty" value="{{company.rxCafeReqQty}}" name="rxCafeReqQty" />
</td>
<td>
<input type="date" class="form-control input1" id="RxCafeController_input" name="rxCafeReqTime" />
</td>
<td>
<input type="text" class="form-control input1" id="RxCafeController_input" name="rxCafeReqOrderNotes" />
</td>
<td>
<select class="form-control input1" ng-model="rxPrice" name="rxCafeReqItemPrice" id="RxCafeController_input">
<option ng-repeat="v in availablePrice " value="{{v}}" ng-selected="{{v}}">{{v}}</option>
</select>
</td>
<td>
<input type="number" class="form-control input1" id="RxCafeController_input" ng-model="rxTotalPrice" value="{{rxPrice*rxQty*0.06}}" ng-disabled="true" name="rxCafeReqTotalPrice" />
</td>
<td>
<input type="button" value="Delete" ng-click="removeRow($index)" name="Delete" />
</td>
</tr>
</tbody>
</table>
<input type="submit" class="button" id="dataTable2_input" value="Add another line" ng-click="addRow('')" />
</div>
</div>

Can you check for loop used in your code,
$http.get("/URL ").then(function(response) {
//$scope.RxCafeLocationArray = response.data.records;
var itemListArray= response.data.records;
for(var i=0;i!=response.data.records.length;i++){
$scope.RxItemDetailArray.push({'itemName':itemListArray[i].u_item_name,'itemPrice':itemListArray[i].u_itemprice_decimal});
console.log('Data from Server- '+JSON.stringify(response.data.records));
}
condition in for loop seems confusing, it should be <=rather than !=

Related

How to Sort the table column both ascending and descending using JQuery?

In the code below I can sort the table only in ascending order. When I click the table header a second time it does not switch the order to descending order.
Can anyone help me how sort the table column in both directions? Is there any alternative way available to sort the textbox value that is inside the table data?
$("#sortcol").click(function() {
const table = document.getElementById('tab_logic');
const headers = table.querySelectorAll('th');
const tableBody = table.querySelector('tbody');
const rows = tableBody.querySelectorAll('tr');
const directions = Array.from(headers).map(function(header) {
return '';
});
const transform = function(index, content) {
const type = headers[index].getAttribute('data-type');
switch (type) {
case 'number':
return parseFloat(content);
case 'string':
default:
return content;
}
};
const sortColumn = function(index) {
const direction = directions[index] || 'asc';
const multiplier = direction === 'asc' ? 1 : -1;
const newRows = Array.from(rows);
newRows.sort(function(rowA, rowB) {
const cellA = rowA.getElementsByTagName("td")[index];
const cellB = rowB.getElementsByTagName("td")[index];
const cellC = $(cellA).find('input').val();
const cellD = $(cellB).find('input').val();
const a = transform(index, cellC);
const b = transform(index, cellD);
switch (true) {
case a > b:
return 1 * multiplier;
case a < b:
return -1 * multiplier;
case a === b:
return 0;
}
});
[].forEach.call(rows, function(row) {
tableBody.removeChild(row);
});
directions[index] = direction === 'asc' ? 'desc' : 'asc';
newRows.forEach(function(newRow) {
tableBody.appendChild(newRow);
});
};
sortColumn(1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tab_logic" style="width: 40%; border: 1px solid black;">
<thead>
<tr>
<th data-type="number">check</th>
<th id="sortcol">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox">
</td>
<td>
<input type="text" Value=" MySQL">
</td>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td>
<input type="text" Value=" Python">
</td>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td>
<input type="text" Value=" Javascript">
</td>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td>
<input type="text" Value=" Angular JS">
</td>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td>
<input type="text" Value=" Csharp">
</td>
</tr>
</tbody>
</table>
your code is perfectly fine only problem is when you are clicking on it direction variable is resetting and 'asc' value is not persisting into an array. please check the below code.
var rows;
var directions;
var headers;
var tableBody;
$(document).ready(function(){
const table = document.getElementById('tab_logic');
headers = table.querySelectorAll('th');
tableBody = table.querySelector('tbody');
rows = tableBody.querySelectorAll('tr');
directions = Array.from(headers).map(function(header) {
return '';
});
})
const transform = function(index, content) {
const type = headers[index].getAttribute('data-type');
switch (type) {
case 'number':
return parseFloat(content);
case 'string':
default:
return content;
}
};
const sortColumn = function(index) {
const direction = directions[index] || 'asc';
const multiplier = direction === 'asc' ? 1 : -1;
const newRows = Array.from(rows);
newRows.sort(function(rowA, rowB) {
const cellA = rowA.getElementsByTagName("td")[index];
const cellB = rowB.getElementsByTagName("td")[index];
const cellC = $(cellA).find('input').val();
const cellD = $(cellB).find('input').val();
const a = transform(index, cellC);
const b = transform(index, cellD);
switch (true) {
case a > b:
return 1 * multiplier;
case a < b:
return -1 * multiplier;
case a === b:
return 0;
}
});
[].forEach.call(rows, function(row) {
tableBody.removeChild(row);
});
newRows.forEach(function(newRow) {
tableBody.appendChild(newRow);
});
directions[index] = direction === 'asc' ? 'desc' : 'asc';
};
$("#sortcol").click(function() {
sortColumn(1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tab_logic" style="width: 40%; border: 1px solid black;">
<thead>
<tr>
<th data-type="number">check</th>
<th id="sortcol">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox">
</td>
<td>
<input type="text" Value=" MySQL">
</td>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td>
<input type="text" Value=" Python">
</td>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td>
<input type="text" Value=" Javascript">
</td>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td>
<input type="text" Value=" Angular JS">
</td>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td>
<input type="text" Value=" Csharp">
</td>
</tr>
</tbody>
</table>

Angular js application shows Syntax Error

I am consuming wcf service into angular js application . I am trying to invoke multi request from angular js application to wcf service . But the problem is when i run the application i got following errors in google chrome console windows .
Uncaught SyntaxError: missing ) after argument list
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.5/$injector/modulerr?
Here is the script code .
///// <reference path="../angular.min.js" />
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
$scope.OperType = 1;
//1 Mean New Entry
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.Tittle = "";
$scope.First_Name = "";
$scope.Last_Name = "";
$scope.Gender = "";
$scope.DOB = "";
$scope.Mobile = "";
$scope.House_No = "";
$scope.Streent_Name = "";
$scope.Country = "";
$scope.Post_Code = "";
$scope.Occupation = "";
}
$scope.CeditCardApplication = function () {
var ApplicationDeatils = {
Tittle: $scope.Tittle,
First_Name: $scope.First_Name,
Last_Name: $scope.Last_Name,
Gender: $scope.Gender,
DOB: $scope.DOB,
Mobile: $scope.Mobile,
House_No: $scope.House_No,
Streent_Name: $scope.Streent_Name,
Country: $scope.Country,
Post_Code: $scope.Post_Code,
Occupation: $scope.Occupation
};
myService.ApplicationDeatilsCheck(ApplicationDeatils).then(function (pl) {
console.log(pl.data)
if (pl.data) {
$scope.msg = "User information is correct !"
myService.ApplicationCreditScoreCheck(ApplicationDeatils1).then(function (p2) {
console.log(p2.data)
if (p2.data) {
$scope.msg = "We can offer you £6000";
}
else {
$scope.msg = "Application failed !";
console.log("Some error Occured" + err);
}
}, function (err) {
$scope.msg = "Application failed!";
console.log("Some error Occured" + err);
});
};
}
}]);
app.service("myService", function ($http) {
this.ApplicationDeatilsCheck = function (ApplicationDeatils) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/CreateCurrentAccountCheck", JSON.stringify(ApplicationDeatils));
}
this.ApplicationCreditScoreCheck = function (ApplicationDeatils) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/cheekCreditScore", JSON.stringify(ApplicationDeatils));
}
})
Here is the HTML CODE ..
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="WebClientModule">
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/CreditCardApplicationScript/ApplicationCheck.js"></script>
</head>
<body >
<table id="tblContainer" data-ng-controller="Web_Client_Controller">
<tr>
<td></td>
</tr>
<tr>
<td>
<table style="border: solid 4px Red; padding: 2px;">
<tr>
<td></td>
<td>
<span>Tittle</span>
</td>
<td>
<input type="text" id="Tittle" data-ng-model="Tittle" required="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Fisrt Name</span>
</td>
<td>
<input type="text" id="first_name" required data-ng-model="First_Name" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Last Name</span>
</td>
<td>
<input type="text" id="last_name" data-ng-model="Last_Name" required="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Gender</span>
</td>
<td>
<input type="text" id="gender" required data-ng-model="Gender" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Date Of Brith</span>
</td>
<td>
<input type="text" id="dob" data-ng-model="DOB" required="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Moblie/Telephone No</span>
</td>
<td>
<input type="text" id="mobile" required data-ng-model="Mobile" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> House No/Door No</span>
</td>
<td>
<input type="text" id="house_no" required data-ng-model="House_No" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Streent Name</span>
</td>
<td>
<input type="text" id="streent_name" required data-ng-model="Streent_Name" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Country</span>
</td>
<td>
<input type="text" id="country" required data-ng-model="Country" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Post Code</span>
</td>
<td>
<input type="text" id="post_code" required data-ng-model="Post_Code" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Occupation</span>
</td>
<td>
<input type="text" id="occupation" required data-ng-model="Occupation" require="" />
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<input type="button" id="CeditCardApplication" value="CeditCardApplication" data-ng-click="CeditCardApplication()" />
</td>
</tr>
</table>
<div style="color: red;">{{msg}}</div>
</td>
</tr>
</table>
</body>
</html>
Here is the screen shot when i run the application ..
The error is correct, you're missing a ) character and a }. Here's the code formatted a little better for ease of reading:
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
$scope.OperType = 1;
//1 Mean New Entry
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.Tittle = "";
$scope.First_Name = "";
$scope.Last_Name = "";
$scope.Gender = "";
$scope.DOB = "";
$scope.Mobile = "";
$scope.House_No = "";
$scope.Streent_Name = "";
$scope.Country = "";
$scope.Post_Code = "";
$scope.Occupation = "";
}
$scope.CeditCardApplication = function () {
var ApplicationDeatils = {
Tittle: $scope.Tittle,
First_Name: $scope.First_Name,
Last_Name: $scope.Last_Name,
Gender: $scope.Gender,
DOB: $scope.DOB,
Mobile: $scope.Mobile,
House_No: $scope.House_No,
Streent_Name: $scope.Streent_Name,
Country: $scope.Country,
Post_Code: $scope.Post_Code,
Occupation: $scope.Occupation
};
myService.ApplicationDeatilsCheck(ApplicationDeatils).then(function (pl) {
console.log(pl.data)
if (pl.data) {
$scope.msg = "User information is correct !"
myService.ApplicationCreditScoreCheck(ApplicationDeatils1).then(function (p2) {
console.log(p2.data)
if (p2.data) {
$scope.msg = "We can offer you £6000";
} else {
$scope.msg = "Application failed !";
console.log("Some error Occured" + err);
}
}, function (err) {
$scope.msg = "Application failed!";
console.log("Some error Occured" + err);
});
};
}); // <-- missing )
} // <-- missing }
}]);
app.service("myService", function ($http) {
this.ApplicationDeatilsCheck = function (ApplicationDeatils) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/CreateCurrentAccountCheck", JSON.stringify(ApplicationDeatils));
}
this.ApplicationCreditScoreCheck = function (ApplicationDeatils) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/cheekCreditScore", JSON.stringify(ApplicationDeatils));
}
});
This is one of those times where indentation and code-readability is super important.

Keys in object are getting removed when i am using ng-repeat

i am using angular ng-repeat to add the set of input values which can be used to give the input.
how i am adding dynamically is i am taking an object and pushing into the ng-repeat variable. In the html each key in the object has a input field
javascript
(function () {
'use strict';
angular.module('myFirstApp', [])
.controller('MyFirstController', function ($scope) {
var flowchart=this;
$scope.conditionslv = [];
flowchart.field1dropdown = [{"FieldName":"","DisplayName":"select"},{"FieldName":"se","DisplayName":"se"},{"qw":"","DisplayName":"qw"}]
flowchart.operatordropdown = [{"OperatorTypeId":'',"OperatorTypeName":"select","WFSubConditions":[]},{"OperatorTypeId":1,"OperatorTypeName":"Greater Than","WFSubConditions":[]}]
flowchart.addconditionrow = function () {
$scope.conditionslv.push({
expression1: '', operatortypeid: '', expressionvalue: "", expression2value: "", comments: ""
});
console.log(JSON.stringify($scope.conditionslv));
}
flowchart.cancelConditons = function () {
flowchart.diagramshow = true;
flowchart.conditions = false;
}
flowchart.saveconditions=function(){
}
});
})();
html
<table>
<th>Field-1</th>
<th>Operator</th>
<th>Field-2</th>
<th>Comments</th>
<tbody>
<tr ng-repeat="i in conditionslv">
<td>{{i}}</td>
<td>
<select ng-model="i.expression1" required>
<option ng-repeat="item in fc.field1dropdown" value="{{item.FieldName}}">{{item.DisplayName}}</option>
</select>
</td>
<td>
<select ng-model="i.operatortypeid" ng-required="true" ng-options="item.OperatorTypeId as item.OperatorTypeName for item in fc.operatordropdown" ></select>
</td>
<td>
<input type="text" ng-model="i.expressionvalue" ng-disabled="i.expression2value!=''||i.operatortypeid>5" >/<select ng-model="i.expression2value" ng-disabled="i.expressionvalue!=''||i.operatortypeid>5" required>
<option ng-repeat="item in fc.field1dropdown" value="{{item.FieldName}}">{{item.DisplayName}}</option>
</select>
</td>
<td>
<textarea rows="1" cols="40" ng-model="i.comments"></textarea><span ng-click="conditionslv.splice($index,1)"
ng-if="conditionslv.length>1"><span class="k-icon k-font-icon k-i-x"></span></span>
</td>
</tr>
</tbody>
</table>
most of the inputs that i am adding are the dropdowns.
the problem is if i select a dropdown value and then again selecting the select option then the key corresponding to the dropdown is getting removed from the object
how the key is getting removed?thanks in advance
This may helpful..
(function () {
'use strict';
angular.module('myFirstApp', [])
.controller('MyFirstController', function ($scope) {
var flowchart=this;
flowchart.conditionslv = [{expression1: '', operatortypeid: '', expressionvalue: "", expression2value: "", comments: ""
}];
flowchart.field1dropdown = [{"FieldName":"ff","DisplayName":"select"},{"FieldName":"se","DisplayName":"se"},{"qw":"","DisplayName":"qw"}]
flowchart.operatordropdown = [{"OperatorTypeId":'',"OperatorTypeName":"select","WFSubConditions":[]},{"OperatorTypeId":1,"OperatorTypeName":"Greater Than","WFSubConditions":[]}]
flowchart.addconditionrow = function (valid) {
if(valid){
flowchart.conditionslv.push({
expression1: '', operatortypeid: '', expressionvalue: "", expression2value: "", comments: ""
});
} console.log(valid);
}
flowchart.cancelConditons = function () {
flowchart.diagramshow = true;
flowchart.conditions = false;
}
flowchart.saveconditions=function(){
}
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myFirstApp" ng-controller="MyFirstController as ctrl">
<form name="addForm" novalidate>
<button ng-click="ctrl.addconditionrow(addForm.$valid)" ng-disabled="addForm.$invalid">Add row</button>
<table>
<th>Field-1</th>
<th>Operator</th>
<th>Field-2</th>
<th>Comments</th>
<tbody>
<tr ng-repeat="i in ctrl.conditionslv">
<td>{{i.expression1}}{{i.operatortypeid}}{{i.expressionvalue}}{{i.expression2value}}{{i.comments}}</td>
<td>
<select ng-model="i.expression1" name="expre" required>
<option ng-repeat="item in ctrl.field1dropdown" value="{{item.FieldName}}">{{item.DisplayName}}</option>
</select>
</td>
<td>
<select ng-model="i.operatortypeid" ng-required="true" ng-options="item.OperatorTypeId as item.OperatorTypeName for item in ctrl.operatordropdown" ></select>
</td>
<td>
<input type="text" ng-model="i.expressionvalue" ng-disabled="i.expression2value!=''||i.operatortypeid>5" >/<select ng-model="i.expression2value" ng-disabled="" ng-required="i.expressionvalue!=''||i.operatortypeid>5 && i.expression2value==''">
<option ng-repeat="item in ctrl.field1dropdown" value="{{item.FieldName}}">{{item.DisplayName}}</option>
</select>
</td>
<td>
<textarea style="width:100px" rows="1" cols="40" ng-model="i.comments" name="comment" required></textarea>
<span ng-click="ctrl.conditionslv.splice($index,1)" ng-if="ctrl.conditionslv.length>1">
<span class="k-icon k-font-icon k-i-x"></span></span>
</td>
</tr>
</tbody>
</table>
</form>
</body>
Working jsfiddle
HTML
<table ng-controller="MyFirstController as fc">
<thead>
<th>Field-1</th>
<th>Operator</th>
<th>Field-2</th>
<th>Comments</th>
</thead>
<tbody>
<tr ng-repeat="i in conditionslv">
<td>
<select ng-model="i.expression1" required>
<option ng-repeat="item in fc.field1dropdown" value="{{item.FieldName}}">{{item.DisplayName}}</option>
</select>
</td>
<td>
<select ng-model="i.operatortypeid" ng-required="true" ng-options="item.OperatorTypeId as item.OperatorTypeName for item in fc.operatordropdown"></select>
</td>
<td>
<input type="text" ng-model="i.expressionvalue" ng-disabled="i.expression2value!=''||i.operatortypeid>5">/
<select ng-model="i.expression2value" ng-disabled="i.expressionvalue!=''||i.operatortypeid>5" required>
<option ng-repeat="item in fc.field1dropdown" value="{{item.FieldName}}">{{item.DisplayName}}</option>
</select>
</td>
<td>
<textarea rows="1" cols="40" ng-model="i.comments"></textarea><span ng-click="conditionslv.splice($index,1)" ng-if="conditionslv.length>1"><span class="k-icon k-font-icon k-i-x"></span></span>
</td>
</tr>
</tbody>
</table>
Controller
angular.module('myFirstApp', [])
.controller('MyFirstController', function($scope) {
var flowchart = this;
$scope.conditionslv = [];
flowchart.field1dropdown = [{
"FieldName": "",
"DisplayName": "select"
}, {
"FieldName": "se",
"DisplayName": "se"
}, {
"qw": "",
"DisplayName": "qw"
}];
flowchart.operatordropdown = [{
"OperatorTypeId": '',
"OperatorTypeName": "select",
"WFSubConditions": []
}, {
"OperatorTypeId": 1,
"OperatorTypeName": "Greater Than",
"WFSubConditions": []
}];
flowchart.addconditionrow = function() {
$scope.conditionslv.push({
expression1: '',
operatortypeid: '',
expressionvalue: "",
expression2value: "",
comments: ""
});
console.log(JSON.stringify($scope.conditionslv));
}
flowchart.cancelConditons = function() {
flowchart.diagramshow = true;
flowchart.conditions = false;
}
flowchart.saveconditions = function() {
}
flowchart.addconditionrow();
});
Need some clarifications :
From where this flowchart.addconditionrow() is executing ?
As you are pushing the single object into $scope.conditionslv array then why are you using ng-repeat ?. you can directly assign object property into the ng-model.
DEMO
angular.module('myApp', [])
.controller('MainController', function($scope) {
var flowchart = this;
$scope.conditionslv = [];
flowchart.field1dropdown = [{
"FieldName": "",
"DisplayName": "select"
}, {
"FieldName": "se",
"DisplayName": "se"
}, {
"qw": "",
"DisplayName": "qw"
}]
flowchart.operatordropdown = [{
"OperatorTypeId": '',
"OperatorTypeName": "select",
"WFSubConditions": []
}, {
"OperatorTypeId": 1,
"OperatorTypeName": "Greater Than",
"WFSubConditions": []
}]
flowchart.addconditionrow = function() {
$scope.conditionslv.push({
expression1: '',
operatortypeid: '',
expressionvalue: "",
expression2value: "",
comments: ""
});
}
flowchart.addconditionrow();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainController as fc">
<table>
<th>Field-1</th>
<th>Operator</th>
<th>Field-2</th>
<th>Comments</th>
<tbody>
<tr ng-repeat="i in conditionslv">
<td>
<select ng-model="i.expression1" required>
<option ng-repeat="item in fc.field1dropdown" value="{{item.FieldName}}">{{item.DisplayName}}</option>
</select>
</td>
<td>
<select ng-model="i.operatortypeid" ng-required="true" ng-options="item.OperatorTypeId as item.OperatorTypeName for item in fc.operatordropdown" ></select>
</td>
<td>
<input type="text" ng-model="i.expressionvalue" ng-disabled="i.expression2value!=''||i.operatortypeid>5" >/<select ng-model="i.expression2value" ng-disabled="i.expressionvalue!=''||i.operatortypeid>5" required>
<option ng-repeat="item in fc.field1dropdown" value="{{item.FieldName}}">{{item.DisplayName}}</option>
</select>
</td>
<td>
<textarea rows="1" cols="40" ng-model="i.comments"></textarea><span ng-click="conditionslv.splice($index,1)"
ng-if="conditionslv.length>1"><span class="k-icon k-font-icon k-i-x"></span></span>
</td>
</tr>
</tbody>
</table>
<div>

Why does the total from last row is not calculating the sum?

I am doing a project that involves making an estimate and adding up does results. I am using the method GET and using some of the the info from the url. Also i am using WordPress to build the Web Page. Problem is that sum of the TOTAL column is not working and showing in the TOTAL row that i made. Is not an error but i think I need to add one more piece of code or change something in the javascript. So why does the id:"total" not showing the sum of the whole column? is the total.value wrong? does the id:"system_total" have a problem?
Here is how the HTML looks like:
<form >
<h2>Cotizacion</h2>
<table class="Cotization">
<tbody>
<tr>
<th style="width:25%;font-size:16px;text-align:center;">Description</th>
<th style="width:15%;" class="qtyhd" title="qtytt">Qty</th>
<th style="width:15%;" class="ratehd" title="ratett">Rate</th>
<th style="width:15%;" class="tlhd" title="totaltt">Total</th>
</tr>
<tr>
<td>PV Grid Tied System</td>
<td> <input id="system_qty" name="system_qty" value="1" type="number" /></td>
<td> <input id="system_rate" name="system_rate" value="0" type="number" /></td>
<td> <output id="system_total"> </output></td>
</tr>
<tr>
<td>Solar Modules 250w</td>
<td> <input id="modules_qty" name="modules_qty" value="0" type="number" /></td>
<td> <input id="modules_rate" name="modules_rate" value="0" type="number" /></td>
<td> <output id="modules_total"> </output></td>
</tr>
<tr>
<td>Inverter</td>
<td> <input id="inverter_qty" name="inverter_qty" value="1" type="number" /></td>
<td> <input id="inverter_rate" name="inverter_rate" value="0" type="number" /></td>
<td> <output id="inverter_total"> </output></td>
</tr>
<tr>
<td>Aluminum Fames</td>
<td> <input id="aluminum_qty" name="aluminum_qty" value="0" type="number" /></td>
<td> <input id="aluminum_rate" name="aluminum_rate" value="0" type="number" /></td>
<td> <output id="aluminum_total"> </output></td>
</tr>
<tr>
<td>Service Disconnect</td>
<td> <input id="servicedt_qty" name="servicedt_qty" value="1" type="number" /></td>
<td> <input id="servicedt_rate" name="servicedt_rate" value="0" type="number" /></td>
<td> <output id="servicedt_total"> </output></td>
</tr>
<tr>
<td>Installation</td>
<td> <input id="installation_qty" name="installation_qty" value="1" type="number" /></td>
<td> <input id="installation_rate" name="installation_rate" value="0" type="number" /></td>
<td> <output id="installation_total"> </output></td>
</tr>
<tr>
<td>Down Payment</td>
<td> <input id="dnpayment_qty" name="dnpayment_qty" value="-1" type="number" /></td>
<td> <input id="dnpayment_rate" name="dnpayment_rate" value="0" type="number" /></td>
<td> <output id="dnpayment_total"> </output></td>
</tr>
<tr>
<td>Total </td>
<td> </td>
<td> </td>
<td> <input id="total" name="total"/></td>
</tr>
</tbody>
</table>
</form>
And here is the javascript that might have the problem:
<script>
document.addEventListener('DOMContentLoaded', function () {
var system_size = Number(getParameterByName('system_size'));
var system_rate_input = document.getElementById('system_rate');
var modules_qty = document.getElementById('modules_qty');
var aluminum_qty = document.getElementById('aluminum_qty');
var systemTotal = Number(document.getElementById('system_total').innerText);
var moduleTotal = Number(document.getElementById('modules_total').innerText);
var inverterTotal = Number(document.getElementById('inverter_total').innerText);
var aluminumTotal = Number(document.getElementById('aluminum_total').innerText);
var servicedtTotal = Number(document.getElementById('servicedt_total').innerText);
var installationTotal = Number(document.getElementById('installation_total').innerText);
var dnpaymentTotal = Number(document.getElementById('dnpayment_total').innerText);
var total = document.getElementById('total');
modules_qty.value = Number(system_size) * 4;
aluminum_qty.value = Number(modules_qty.value);
system_rate_input.value = 2.9 * 1000 * 1.2 * system_size;
updateSystemTotal()
updateModulesTotal()
updateInverterTotal()
updateAluminumTotal()
updateServiceTotal()
updateInstallationTotal()
updateDownPaymentTotal()
total.value = Number(systemTotal) + Number(moduleTotal) + Number(inverterTotal) + Number(aluminumTotal) + Number(servicedtTotal) + Number(installationTotal) + Number(dnpaymentTotal);
})
// FIRST ROW
function updateSystemTotal() {
var output = document.getElementById('system_total');
var quantity = Number(document.getElementById('system_qty').value);
var system_rate = Number(document.getElementById('system_rate').value);
output.innerText = quantity * system_rate;
}
document.getElementById('system_rate').addEventListener('change', updateSystemTotal)
document.getElementById('system_qty').addEventListener('change', updateSystemTotal)
// Second ROW
function updateModulesTotal() {
var output = document.getElementById('modules_total');
var quantity = Number(document.getElementById('modules_qty').value);
var modules_rate = Number(document.getElementById('modules_rate').value);
output.innerText = quantity * modules_rate;
}
document.getElementById('modules_rate').addEventListener('change', updateModulesTotal)
document.getElementById('modules_qty').addEventListener('change', updateModulesTotal)
// Third ROW
function updateInverterTotal() {
var output = document.getElementById('inverter_total');
var quantity = Number(document.getElementById('inverter_qty').value);
var inverter_rate = Number(document.getElementById('inverter_rate').value);
output.innerText = quantity * inverter_rate;
}
document.getElementById('inverter_rate').addEventListener('change', updateInverterTotal)
document.getElementById('inverter_qty').addEventListener('change', updateInverterTotal)
// Fourth ROW
function updateAluminumTotal() {
var output = document.getElementById('aluminum_total');
var quantity = Number(document.getElementById('aluminum_qty').value);
var aluminum_rate = Number(document.getElementById('aluminum_rate').value);
output.innerText = quantity * aluminum_rate;
}
document.getElementById('aluminum_rate').addEventListener('change', updateAluminumTotal)
document.getElementById('aluminum_qty').addEventListener('change', updateAluminumTotal)
// Fith ROW
function updateServiceTotal() {
var output = document.getElementById('servicedt_total');
var quantity = Number(document.getElementById('servicedt_qty').value);
var servicedt_rate = Number(document.getElementById('servicedt_rate').value);
output.innerText = quantity * servicedt_rate;
}
document.getElementById('servicedt_rate').addEventListener('change', updateServiceTotal)
document.getElementById('servicedt_qty').addEventListener('change', updateServiceTotal)
// Six ROW
function updateInstallationTotal() {
var output = document.getElementById('installation_total');
var quantity = Number(document.getElementById('installation_qty').value);
var installation_rate = Number(document.getElementById('installation_rate').value);
output.innerText = quantity * installation_rate;
}
document.getElementById('installation_rate').addEventListener('change', updateInstallationTotal)
document.getElementById('installation_qty').addEventListener('change', updateInstallationTotal)
//Seventh ROW
function updateDownPaymentTotal() {
var output = document.getElementById('dnpayment_total');
var quantity = Number(document.getElementById('dnpayment_qty').value);
var dnpayment_rate = Number(document.getElementById('dnpayment_rate').value);
output.innerText = quantity * dtpayment_rate;
}
document.getElementById('dnpayment_rate').addEventListener('change', updateDownPaymentTotal)
document.getElementById('dnpayment_qty').addEventListener('change', updateDownPaymentTotal)
// DON't TOUCH ANYTHING BELOW THIS POINT!!!
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
</script>
var systemTotal = Number(document.getElementById('system').innerText);
There is no element called "system" in the snippets you provided. Are you sure you don't need to get the value from "system_total"?
Edit:
Total is showing 0 at the beginning, because the subtotals aren't initialized. To fix this, you can use your update functions before calculating the total.
document.addEventListener('DOMContentLoaded', function () {
var system_size = Number(getParameterByName('system_size'));
var system_rate_input = document.getElementById('system_rate');
var modules_qty = document.getElementById('modules_qty');
var aluminum_qty = document.getElementById('aluminum_qty');
var total = document.getElementById('total');
modules_qty.value = Number(system_size) * 4;
aluminum_qty.value = Number(modules_qty.value);
system_rate_input.value = 2.9 * 1000 * 1.2 * system_size;
updateSystemTotal();
updateModulesTotal();
updateInverterTotal();
updateAluminumTotal();
updateServiceTotal();
updateInstallationTotal();
updateDownPaymentTotal();
updateTotal();
})
function updateTotal() {
var total = document.getElementById('total');
var systemTotal = Number(document.getElementById('system_total').innerText);
var moduleTotal = Number(document.getElementById('modules_total').innerText);
var inverterTotal = Number(document.getElementById('inverter_total').innerText);
var aluminumTotal = Number(document.getElementById('aluminum_total').innerText);
var servicedtTotal = Number(document.getElementById('servicedt_total').innerText);
var installationTotal = Number(document.getElementById('installation_total').innerText);
var dnpaymentTotal = Number(document.getElementById('dnpayment_total').innerText);
total.value = Number(systemTotal) + Number(moduleTotal) + Number(inverterTotal) + Number(aluminumTotal) + Number(servicedtTotal) + Number(installationTotal) + Number(dnpaymentTotal);
}
Further, you are updating the subtotals as soon as the user edits Quantities or Rates, but you are not updating the "Total" value.
You could call updateTotal() in your own update functions to solve this issue:
function updateSystemTotal() {
var output = document.getElementById('system_total');
var quantity = Number(document.getElementById('system_qty').value);
var system_rate = Number(document.getElementById('system_rate').value);
output.innerText = quantity * system_rate;
updateTotal();
}
Copy my code and Run it :
javascript(1.js) :
function rr() {
var system_size = document.getElementById('system_qty').value;
var system_rate_input = document.getElementById('system_rate').value;
var modules_qty = document.getElementById('modules_qty').value;
var modules_rate = document.getElementById('modules_rate').value;
var inverter_qty = document.getElementById('inverter_qty').value;
var inverter_rate = document.getElementById('inverter_rate').value;
var aluminum_qty = document.getElementById('aluminum_qty').value;
var aluminum_rate = document.getElementById('aluminum_rate').value;
var servicedt_qty = document.getElementById('servicedt_qty').value;
var servicedt_rate = document.getElementById('servicedt_rate').value;
var installation_qty = document.getElementById('installation_qty').value;
var installation_rate = document.getElementById('installation_rate').value;
var dnpayment_qty = document.getElementById('dnpayment_qty').value;
var dnpayment_rate = document.getElementById('dnpayment_rate').value;
var systemTotal = system_size * system_rate_input;
document.getElementById('system_total').innerHTML = systemTotal;
var moduleTotal = modules_rate * modules_qty;
document.getElementById('modules_total').innerHTML = moduleTotal;
var inverterTotal = inverter_qty * inverter_rate;
document.getElementById('inverter_total').innerHTML = inverterTotal;
var aluminumTotal =aluminum_qty * aluminum_rate;
document.getElementById('aluminum_total').innerHTML = aluminumTotal;
var servicedtTotal = servicedt_qty * servicedt_rate;
document.getElementById('servicedt_total').innerHTML = servicedtTotal;
var installationTotal = installation_qty * installation_rate;
document.getElementById('installation_total').innerHTML = installationTotal;
var dnpaymentTotal = dnpayment_qty * dnpayment_rate;
document.getElementById('dnpayment_total').innerHTML = dnpaymentTotal;
var Total = document.getElementById('total');
aluminum_qty = system_size * 4;
system_rate_input = 2.9 * 1000 * 1.2 * system_size;
Total.value = systemTotal + moduleTotal + inverterTotal+ aluminumTotal + servicedtTotal+ installationTotal + dnpaymentTotal;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="1.js"></script>
<form name="frm" >
<h2>Cotizacion</h2>
<table class="Cotization">
<tbody>
<tr>
<th style="width:25%;font-size:16px;text-align:center;">Description</th>
<th style="width:15%;" class="qtyhd" title="qtytt">Qty</th>
<th style="width:15%;" class="ratehd" title="ratett">Rate</th>
<th style="width:15%;" class="tlhd" title="totaltt">Total</th>
</tr>
<tr>
<td>PV Grid Tied System</td>
<td> <input id="system_qty" name="system_qty" value="1" type="number" /></td>
<td> <input id="system_rate" name="system_rate" value="0" type="number" /></td>
<td> <output id="system_total"> </output></td>
</tr>
<tr>
<td>Solar Modules 250w</td>
<td> <input id="modules_qty" name="modules_qty" value="0" type="number" /></td>
<td> <input id="modules_rate" name="modules_rate" value="0" type="number" /></td>
<td> <output id="modules_total"> </output></td>
</tr>
<tr>
<td>Inverter</td>
<td> <input id="inverter_qty" name="inverter_qty" value="1" type="number" /></td>
<td> <input id="inverter_rate" name="inverter_rate" value="0" type="number" /></td>
<td> <output id="inverter_total"> </output></td>
</tr>
<tr>
<td>Aluminum Fames</td>
<td> <input id="aluminum_qty" name="aluminum_qty" value="0" type="number" /></td>
<td> <input id="aluminum_rate" name="aluminum_rate" value="0" type="number" /></td>
<td> <output id="aluminum_total"> </output></td>
</tr>
<tr>
<td>Service Disconnect</td>
<td> <input id="servicedt_qty" name="servicedt_qty" value="1" type="number" /></td>
<td> <input id="servicedt_rate" name="servicedt_rate" value="0" type="number" /></td>
<td> <output id="servicedt_total"> </output></td>
</tr>
<tr>
<td>Installation</td>
<td> <input id="installation_qty" name="installation_qty" value="1" type="number" /></td>
<td> <input id="installation_rate" name="installation_rate" value="0" type="number" /></td>
<td> <output id="installation_total"> </output></td>
</tr>
<tr>
<td>Down Payment</td>
<td> <input id="dnpayment_qty" name="dnpayment_qty" value="-1" type="number" /></td>
<td> <input id="dnpayment_rate" name="dnpayment_rate" value="0" type="number" /></td>
<td> <output id="dnpayment_total"> </output></td>
</tr>
<tr>
<td>Total </td>
<td> </td>
<td> </td>
<td> <input value="" id="total" name="total"/></td>
</tr>
</tbody>
</table>
</form>
<button id="btn" onclick="rr()">Click</button>
</body>
</html>

Angular js model value changes are not reflected in ui

Values in the UI doesn't change even after executing the code in controller.
It displays the initial values with out a problem.
I've tried calling $scope.$apply() at the end of each function (submit and transfer) but it didn't work(it only gave an error with the $http.post()). What am i missing here?
app.controller('RegisterController', ['$scope','$http', function($scope,$http) {
$scope.user = {
email: 'admin#blah.com',
password1: '1qaz2wsx',
password2:'1qaz2wsx',
password:'1qaz2wsx',
username:'Admin',
profile_picture:'',
dobDay:'12',
dobMonth:'12',
dobYear:'1993',
date_of_birth:'',
stateMessage:'',
messageColor:'white',
};
var transfer = function(){
$http.post('http://localhost/cw/index.php/rest/resource/user/action/create',$scope.user).then(function successCallback(response) {
if(response.data.status!=null){
if(response.data.status=='success'){
$scope.user.stateMessage = 'success';
$scope.user.messageColor = "green";
}
else if(response.data.status=='failure'){
$scope.user.stateMessage = response.data.message;
$scope.user.messageColor = "red";
}
}
},function errorCallback(response) {
$scope.user.stateMessage = "Error occured.";
$scope.user.messageColor = "red";
});
};
$scope.submit = function(){
$scope.user.stateMessage="";
$scope.user.messageColor="white";
var proceed = true;
if(!validateFields()){
$scope.user.stateMessage = "All fields must be filled!";
$scope.user.messageColor = "red";
proceed = false;
}
if(validateDate($scope.user.dobDay,$scope.user.dobMonth,$scope.user.dobYear)){
$scope.user.date_of_birth= $scope.user.dobYear+"-"+$scope.user.dobMonth+"-"+$scope.user.dobDay;
}else {
proceed = false;
$scope.user.stateMessage = "Date is invalid!";
$scope.user.messageColor = "red";
}
if($scope.user.password1!=$scope.user.password2){
proceed = false;
$scope.user.stateMessage = "Passwords don't match!";
$scope.user.messageColor = "red";
}else $scope.user.password = $scope.user.password1;
if(proceed){
var file = document.getElementById('filePicker').files[0];
reader = new FileReader();
reader.onloadend = function(e) {
$scope.user.profile_picture = JSON.stringify(e.target.result);
$scope.$apply();
console.log($scope.user.profile_picture);
transfer();
}
reader.readAsDataURL(file);
}
function validateFields(){
/*some form validation*/
return true;
}
function validateDate(day,month,year){
/*some date validation*/
return true;
}
}
}]);
HTML code
<div ng-controller="RegisterController">
<span style="background-color:{{user.messageColor}}"><h4>{{user.stateMessage}}</h4></span>
</div>
<table style="text-align: left" ng-controller="RegisterController">
<tr>
<td>
Username
</td>
<td>
<input type="text" ng-bind="user.username" ng-model="user.username">
</td> <td> </td><td> </td>
</tr>
<tr>
<td>
Email
</td>
<td>
<input type="email" ng-bind="user.email" ng-model="user.email">
</td> <td> </td><td> </td>
</tr>
<tr>
<td>
Password
</td>
<td>
<input type="password" ng-bind="user.password1" ng-model="user.password1">
</td> <td> </td><td> </td>
</tr>
<tr>
<td>
Retype password
</td>
<td>
<input type="password" ng-bind="user.password2" ng-model="user.password2">
</td> <td> </td><td> </td>
</tr>
<tr>
<td>
Date of Birth
</td>
<td>
<input type="text" ng-bind="user.dobDay" ng-model="user.dobDay" value="DD" size="2" maxlength="2">
<input type="text" ng-bind="user.dobMonth" ng-model="user.dobMonth" value="MM" size="2" maxlength="2">
<input type="text" ng-bind="user.dobYear" ng-model="user.dobYear" value="YYYY" size="4" maxlength="4">
</td>
</tr>
<tr>
<td>
Profile picture
</td>
<td>
<input id="filePicker" type="file" ng-bind="user.profile_picture" ng-model="user.profile_picture" accept="image/*">
</td>
</tr>
<tr>
<td></td>
<td style="float:left">
<button ng-click="submit()">Submit</button>
</td>
</tr>
</table>
It seems like i cannot use the same controller in 2 instances.
Moving the status div in to the table assigned with the controller worked for me. There are ways to share data between controllers by using a service but i won't go there since this is only for a coursework.
AngularJS: share the data of the same controller in two different, not nested parts of the page

Categories

Resources