Vuejs sum on event change - javascript

I have following code that sum price of product to existed number when user increase the quantity of product. But the issue with my code is if user decrease the amount price still gets increased.
Code
html
<el-input-number style="width: 100%;" ref="amount" v-on:change="amoutChanged($event, row)" v-model="row.amount" :min="1"></el-input-number>
script
data() {
return {
subtotal: 0,
}
},
methods: {
amoutChanged: function(event, row) {
console.log('amount row: ', row);
console.log('amount event: ', event);
// ISSUE: regardes that user increase or decrease the amount number this price gets increased
this.subtotal = parseInt(this.subtotal) + parseInt(row.price);
},
}
Console results
amount row: {barcoded: "8995078803078", …}
amount: (...)
barcode_id: (...)
barcoded: "8995078803078"
price: (...)
product: (...)
amount event: 2 // this is amount input by user
Question
How to properly increase and decrease price based on user action?

I have done it like this:
I changed subtotal to an computed propertie and sum it with .reduce() and i added a new property called singlePrice so we can multiply with it
var Main = {
data() {
return {
serial_numbers: [{
barcode_id: '45634643',
product: 'dfgs546',
amount: 1,
price: 100,
singlePrice: 100,
},{
barcode_id: '23523fd',
product: 'rgdg46546',
amount: 1,
price: 100,
singlePrice: 100,
},{
barcode_id: 'fdghdh',
product: '345634643',
amount: 1,
price: 100,
singlePrice: 100,
}],
total: 0,
num1: 1
};
},
computed: {
subtotal(){
return this.serial_numbers.reduce((a,v)=> a + v.price,0)
}
},
methods: {
addRow() {
var barcodes = document.createElement('tr');
this.serial_numbers.push({
barcode_id: '675476547',
product: 'hjfgj67',
amount: 1,
price: 100,
singlePrice: 100,
});
},
removeElement: function(index) {
this.serial_numbers.splice(index, 1);
},
amountChanged($event, index){
let amount = $event;
this.serial_numbers[index].amount = amount;
this.serial_numbers[index].price = this.serial_numbers[index].singlePrice * amount;
}
}
};
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
#import url("//unpkg.com/element-ui#1.4.0/lib/theme-default/index.css");
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui#1.4.0/lib/index.js"></script>
<div id="app">
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<td><strong>Serial Number</strong></td>
<td><strong>Product</strong></td>
<td><strong>Amount</strong></td>
<td><strong>Price</strong></td>
<td width="50"></td>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in serial_numbers" :key="index">
<td>
<el-input ref="barcoded" v-model="row.barcode_id"></el-input>
</td>
<td>
<el-input ref="product" v-model="row.product" readonly></el-input>
</td>
<td>
<el-input-number style="width: 100%;" ref="amount" #change="amountChanged($event, index)" v-model="row.amount" :min="1"></el-input-number>
</td>
<td>
<el-input ref="price" v-model="row.price" readonly></el-input>
</td>
<td>
<el-link :underline="false" type="danger" v-on:click="removeElement(index);" style="cursor: pointer"><i class="fa-2x el-icon-remove"></i></el-link>
</td>
</tr>
</tbody>
</table>
<div>
<el-button type="primary" class="button btn-primary" round #click="addRow"><i class="el-icon-circle-plus"></i> Add row</el-button>
</div>
<el-row :gutter="10">
<el-col :span="8" :offset="16">
<table class="table table-bordered table-striped table-hover">
<tbody>
<tr>
<th width="100"><strong>Sub total</strong></th>
<td>
{{subtotal}}
</td>
</tr>
<tr>
<th width="100"><strong>Total</strong></th>
<td>
{{total}}
</td>
</tr>
</tbody>
</table>
</el-col>
</el-row>
</div>

Related

Vuejs get $refs value in methods

I have multiple rows and I wish to get input value inside my tr refs but it returns undefined.
Code
Component
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<td><strong>Serial Number</strong></td>
<td><strong>Product</strong></td>
<td><strong>Amount</strong></td>
<td><strong>Price</strong></td>
<td width="50"></td>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in serial_numbers" :key="index">
<td>
<el-input ref="barcoded" v-model="row.barcode_id"></el-input>
</td>
<td>
<el-input ref="product" v-model="row.product"></el-input>
</td>
<td>
<el-input ref="amount" v-model="row.amount"></el-input>
</td>
<td>
<el-input ref="price" v-model="row.price" readonly></el-input>
</td>
<td>
<el-link v-on:click="removeElement(index);" style="cursor: pointer">Remove</el-link>
</td>
</tr>
</tbody>
</table>
<div>
<el-button type="primary" class="button btn-primary" round #click="addRow">Add row</el-button>
</div>
Script
methods: {
focusInput() {
this.$refs.barcode_id.focus();
},
addRow() {
var barcodes = document.createElement('tr');
this.serial_numbers.push({
barcode_id: '',
product: '',
amount: '',
price: ''
});
// try to get value of barcode input
console.log(this.refs.barcoded); // undefined
this.$nextTick(function () {
const nbBarcodes = this.$refs.barcoded.length;
this.$refs.barcoded[nbBarcodes - 1].focus();
});
},
}
Any idea?
Update
Demo
Using the serial_numbers object instead of refs
console.log(this.serial_numbers[this.serial_numbers.length - 1]);
// this was moved from above
this.serial_numbers.push({
barcode_id: '',
product: '',
amount: '',
price: ''
});
You should push the new element after retrieving the values you need
https://codepen.io/albertor24/pen/wvKYxOg

Vue js for loop with a condition

I have an object that look like this:
groupedContacts:
{
4: [
{name: 'foo'},
{name: 'bar'}
],
6: [
{name: 'foo bar'},
]
}
Then I have an other array:
companyList.models:
models: [
{id:4, name: 'company A'},
{id:6, name: 'company B'},
]
So the Id's in my companies resemble the keys in my groupedContacts, in 1 array I have the company names and in the other I have the contacts of the companies.
Now I want to show them in multiple tables ofcourse like this
Table 1
Company A (id4)
- foo
- bar
Table2
Company B (id6)
- foo bar
Here's my code, unfortunately I get my 2 tables of my 2 companies but no contacts. And I get no errors whatsoever:
<div
v-for="(company, key) in companyList.models"
:key="key"
class="table table--hover mt-4"
>
<h4 class="mb-4" v-html="company.name" />
<table>
<thead>
<tr>
<th class="text-left" v-html="__t('name')" />
</tr>
</thead>
<tbody
v-for="(groupContacts, key) in groupedContacts"
:key="key"
v-if="company.id === key"
>
<tr
v-for="(contact, contactKey) in groupContacts"
:key="contactKey"
>
<td v-html="contact.name" />
</tr>
</tbody>
</table>
</div>
This is my result in my browser:
I recommend to use a computed property called companies as follows :
computed: {
companies() {
return this.models.map(c => {
c.groups = this.groupContacts[c.id];
return c;
})
}
}
then loop through it like :
<div v-for="(company, key) in companies" :key="key" class="table table--hover mt-4">
<h4 class="mb-4">{{company.name}}</h4>
<table>
<thead>
<tr>
<th class="text-left">Name</th>
</tr>
</thead>
<tbody>
<tr v-for="(contact, contactKey) in company.groups" :key="contactKey">
<td> {{contact.name}}</td>
</tr>
</tbody>
</table>
</div>
new Vue({
el: '#app',
data() {
return {
groupContacts:
{
4: [{
name: 'foo'
},
{
name: 'bar'
}
],
6: [{
name: 'foo bar'
}, ]
},
models: [{
id: 4,
name: 'company A'
},
{
id: 6,
name: 'company B'
},
]
}
},
computed: {
companies() {
return this.models.map(c => {
c.groups = this.groupContacts[c.id];
return c;
})
}
}
})
<body>
<div id="app">
<div v-for="(company, key) in companies" :key="key" class="table table--hover mt-4">
<h4 class="mb-4">{{company.name}}</h4>
<table>
<thead>
<tr>
<th class="text-left">Name</th>
</tr>
</thead>
<tbody>
<tr v-for="(contact, contactKey) in company.groups" :key="contactKey">
<td> {{contact.name}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue#2.x/dist/vue.js"></script>
mixing v-if with v-for should be avoided (as stated in the Vue.js docs).
Following the recommendation from the docs, you could use a computed property for this case:
<template>
<div>
<div v-for="(company, i) in companyContacts" :key="`company_${i}`" class="table table--hover mt-4">
<h4 class="mb-4" v-html="company.name" />
<table>
<thead>
<tr>
<th class="text-left" v-html="__t('name')" />
</tr>
</thead>
<tbody>
<tr v-for="(contact, j) in company.contacts" :key="`company_${i}_contact_${j}`">
<td v-html="contact.name" />
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
export default {
computed: {
companyContacts() {
return this.companyList.models.map(model => {
model.contacts = this.groupContacts[model.id]
return model
})
}
},
data: () => {
groupedContacts: {
4: [{
name: 'foo'
},
{
name: 'bar'
}
],
6: [{
name: 'foo bar'
}, ]
},
companyList: {
models: [{
id: 4,
name: 'company A'
},
{
id: 6,
name: 'company B'
},
]
}
}
}
</script>
Hope this helps!

Component template should contain exactly one root element nuxt

I'm not sure what could be the issue here but I'm using nuxt to make a SPA app. and I'm getting an error from an already compiled piece of code I got from codepen. link to codepen
https://codepen.io/jjelic/pen/yevNLZ?editors=1010
When I try this code my my nuxt app I get an error.
I've added a file called monitor.vue in pages folder and added the html and js like so
Is this root element error common as I have never encountered it before with html and how can I avoid?
Vue.filter('currencyDisplay', {
// model -> view
read: function(val) {
if (val > 0) {
return accounting.formatMoney(val, "$", 2, ".", ",");
}
},
// view -> model
write: function(val, oldVal) {
return accounting.unformat(val, ",");
}
});
Vue.directive('sortable', {
twoWay: true,
deep: true,
bind: function() {
var that = this;
var options = {
draggable: Object.keys(this.modifiers)[0]
};
this.sortable = Sortable.create(this.el, options);
console.log('sortable bound!')
this.sortable.option("onUpdate", function(e) {
that.value.splice(e.newIndex, 0, that.value.splice(e.oldIndex, 1)[0]);
});
this.onUpdate = function(value) {
that.value = value;
}
},
update: function(value) {
this.onUpdate(value);
}
});
var vm = new Vue({
el: '#app',
data: {
rows: [
//initial data
{
qty: 5,
description: "Something",
price: 55.20,
tax: 10
},
{
qty: 2,
description: "Something else",
price: 1255.20,
tax: 20
},
],
total: 0,
grandtotal: 0,
taxtotal: 0,
delivery: 40
},
computed: {
total: function() {
var t = 0;
$.each(this.rows, function(i, e) {
t += accounting.unformat(e.total, ",");
});
return t;
},
taxtotal: function() {
var tt = 0;
$.each(this.rows, function(i, e) {
tt += accounting.unformat(e.tax_amount, ",");
});
return tt;
}
},
methods: {
addRow: function(index) {
try {
this.rows.splice(index + 1, 0, {});
} catch (e) {
console.log(e);
}
},
removeRow: function(index) {
this.rows.splice(index, 1);
},
getData: function() {
$.ajax({
context: this,
type: "POST",
data: {
rows: this.rows,
total: this.total,
delivery: this.delivery,
taxtotal: this.taxtotal,
grandtotal: this.grandtotal,
},
url: "/api/data"
});
}
}
});
<template>
<div class="panel-body" id="app">
<table class="table table-hover">
<thead>
<tr>
<th style="width: 20px;">No.</th>
<th>Description</th>
<th style="width: 80px;">Qty</th>
<th style="width: 130px;" class="text-right">Price</th>
<th style="width: 90px;">Tax</th>
<th style="width: 130px;">Total</th>
<th style="width: 130px;"></th>
</tr>
</thead>
<tbody v-sortable.tr="rows">
<tr v-for="row in rows" track-by="$index">
<td>
{{ $index +1 }}
</td>
<td>
<input class="form-control" v-model="row.description" />
</td>
<td>
<input class="form-control" v-model="row.qty" number />
</td>
<td>
<input class="form-control text-right" v-model="row.price | currencyDisplay" number data-type="currency" />
</td>
<td>
<select class="form-control" v-model="row.tax">
<option value="0">0%</option>
<option value="10">10%</option>
<option value="20">20%</option>
</select>
</td>
<td>
<input class="form-control text-right" :value="row.qty * row.price | currencyDisplay" v-model="row.total | currencyDisplay"
number readonly />
<input type="hidden" :value="row.qty * row.price * row.tax / 100" v-model="row.tax_amount | currencyDisplay"
number />
</td>
<td>
<button class="btn btn-primary btn-xs" #click="addRow($index)">add row</button>
<button class="btn btn-danger btn-xs" #click="removeRow($index)">remove row</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" class="text-right">TAX</td>
<td colspan="1" class="text-right">{{ taxtotal | currencyDisplay }}</td>
<td></td>
</tr>
<tr>
<td colspan="5" class="text-right">TOTAL</td>
<td colspan="1" class="text-right">{{ total | currencyDisplay }}</td>
<td></td>
</tr>
<tr>
<td colspan="5" class="text-right">DELIVERY</td>
<td colspan="1" class="text-right"><input class="form-control text-right" v-model="delivery | currencyDisplay"
number /></td>
<td></td>
</tr>
<tr>
<td colspan="5" class="text-right"><strong>GRANDTOTAL</strong></td>
<td colspan="1" class="text-right"><strong>{{ grandtotal = total + delivery | currencyDisplay }}</strong></td>
<td></td>
</tr>
</tfoot>
</table>
<button #click="getData()">SUBMIT DATA</button>
<pre>{{ $data | json }}</pre>
</div>
</template>
This problem is actually a very simple problem. I don't know vue, but the render method has the same limits of react's one: every component must have only one root element in its template.
This means that a situation like this isn't accepted:
<template>
<div></div>
<div></div>
</template>
But like this is correct:
<template>
<div></div>
</template>
This means that surely, somehow in the code you didn't show us, you're putting two elements as root of your template

Calculate sum of dynamically added values with vuejs

I am dynamically adding new row with selects and inputs in table if option is selected in first column of last row.
It looks like this https://jsfiddle.net/zgykgery/ so when you select 'Service' new row is added and total price of that row is calculated taking service price, default 10% discount and amount.
I am getting service price a bit clumsy with
:value="item.id+'|'+item.price"
so I have filter to take it from value.
But it works and now I don't know how I can loop through all rows and sum price of service without dicount, sum discount and then full price with servce price and discount.
I know I should use computed properties or watcher but don't know how.
How can I compute sum of those values in table and display them in smaller table below?
Update
I am new in vue and didn't use computed properties so this is what I tried but without success:
var Main = {
data() {
return {
rows_top: [{
service: '',
position: '',
visit: '',
amount: '',
discount: 10
}],
services: [{
id: 1,
name: 'Service1',
price: 100
},
{
id: 2,
name: 'Service2',
price: 200
},
{
id: 3,
name: 'Service3',
price: 300
},
],
total_discount: 0,
total_full_price: 0
}
},
methods: {
addRow(row, index) {
// console.log(row)
if (this.rows_top[this.rows_top.length - 1].service !== '') {
this.rows_top.push({
service: '',
position: '',
visit: '',
amount: '',
discount: 10
})
}
},
deleteRow(index) {
this.rows_top.splice(index, 1)
}
},
computed: {
total_price: () => {
if (this.rows_top) {
return this.rows_top.map((r) => {
return r.amount * this.$options.filters.after_line(r.service)
})
}
}
},
filters: {
after_line: (value) => {
if (!value) return ''
let after = value.split('|')
return after.pop()
}
}
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
#import url("//unpkg.com/element-ui#2.0.11/lib/theme-chalk/index.css");
table {
border-collapse: collapse
}
table,
th,
td {
border: 1px solid #ddd
}
th,
td {
padding: 5px
}
tr:nth-child(odd) {
background-color: #f9f9f9
}
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui#2.2.0/lib/index.js"></script>
<div id="app">
<template>
<table>
<thead>
<tr>
<th>Service</th>
<th>Position</th>
<th>Visit</th>
<th>Amount</th>
<th>Price</th>
<th>Discount %</th>
<th>Full price</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in rows_top">
<td>
<el-select placeholder="Select" filterable="filterable" #change="addRow(row, index)" v-model="row.service">
<el-option v-for="item in services" :key="item.id" :label="item.name" :value="item.id+'|'+item.price"></el-option>
</el-select>
</td>
<td>
<el-select placeholder="Select" v-model="row.position" multiple="multiple" filterable="filterable" allow-create="allow-create" #change="checkNumber(result, index)"></el-select>
</td>
<td>
<el-select placeholder="Select" v-model="row.visit" allow-create="allow-create" filterable="filterable">
<el-option v-for="i in 10" :key="i" :label="i" :value="i"></el-option>
</el-select>
</td>
<td>
<el-select placeholder="Select" v-model="row.amount" allow-create="allow-create" filterable="filterable">
<el-option v-for="i in 30" :key="i" :label="i" :value="i"></el-option>
</el-select>
</td>
<td>{{ row.service | after_line }}</td>
<td>
<el-input v-model="row.discount"></el-input>
</td>
<td><span v-if="row.service && row.amount">{{ ($options.filters.after_line(row.service) * row.amount - (($options.filters.after_line(row.service) * row.amount) / 100) * row.discount).toFixed(2) }}</span><span v-else-if="row.service">{{ ($options.filters.after_line(row.service) - ($options.filters.after_line(row.service) / 100) * row.discount).toFixed(2) }}</span>
<el-button v-if="row.service" icon="el-icon-delete" size="mini" #click="deleteRow(index)" class="push-right"></el-button>
</td>
</tr>
</tbody>
</table><br/>
<table>
<tr>
<td>Total price</td>
<td>{{ total_price }}</td>
</tr>
<tr>
<td>Total discount</td>
<td>{{ total_discount }}</td>
</tr>
<tr>
<td>Total full price</td>
<td>{{ total_full_price }}</td>
</tr>
</table>
</template>
</div>
Here is also updated fiddle and total price is still empty on change https://jsfiddle.net/zgykgery/21/
As #Roy J said, just use a computed function to get you the values of your calculation, knowing that it will automatically change when the data from item changes
EDIT: a simple method is more designed in the case when you use a v-for loop
methods: {
priceID (item) {
return item.id + '|' + item.price
}
}
And you would use it simply like that in your Vue
<tr v-for="(row, index) in rows_top">
<td>
<el-select placeholder="Select" filterable="filterable" #change="addRow(row, index)" v-model="row.service">
<el-option v-for="item in services" :key="item.id" :label="item.name" :value="priceID(item)"></el-option>
</el-select>
</td>
...

Populate an input when checkbox is checked from ngRepeat

I'm trying to populate an input two ways. The first method is to simply type an amount into the input, which works perfectly. The second method (which I'm struggling with) is to check the checkbox generated within the ngRepeat directive.
The desired behavior is that the checkbox will take the value of item.amount from the JSON data and populate the input with that value. Here is the markup:
<table class="table table-striped header-fixed" id="invoiceTable">
<thead>
<tr>
<th class="first-cell">Select</th>
<th class="inv-res2">Invoice #</th>
<th class="inv-res3">Bill Date</th>
<th class="inv-res4">Amount</th>
<th class="inv-res5">Amount to Pay</th>
<th class="inv-res6"></th>
</tr>
</thead>
<tbody>
<tr ng-if="invoices.length" ng-repeat="item in invoices | filter: {status:'Unpaid'}">
<td class="first-cell"><input type="checkbox" /></td>
<td class="inv-res2">{{item.invoiceNum}}</td>
<td class="inv-res3">{{item.creationDate}}</td>
<td class="inv-res4" ng-init="invoices.total.amount = invoices.total.amount + item.amount">{{item.amount | currency}}</td>
<td class="inv-res5">$
<input ng-validate="number" type="number" class="input-mini" ng-model="item.payment" ng-change="getTotal()" step="0.01" /></td>
</tr>
</tbody>
</table>
<table class="table">
<tbody>
<tr class="totals-row" >
<td colspan="3" class="totals-cell"><h4>Account Balance: <span class="status-error">{{invoices.total.amount | currency }}</span></h4></td>
<td class="inv-res4"><h5>Total to pay:</h5></td>
<td class="inv-res5">{{total | currency}}</td>
<td class="inv-res6"></td>
</tr>
</tbody>
</table>
And here is the JavaScript:
myApp.controller('invoiceList', ['$scope', '$http', function($scope, $http) {
$http.get('assets/js/lib/angular/invoices.json').success(function(data) {
$scope.invoices = data;
});
$scope.sum = function(list) {
var total=0;
angular.forEach(list , function(item){
total+= parseInt(item.amount);
});
return total;
};
$scope.total = 0;
$scope.getTotal = function() {
$scope.total = 0;
$scope.invoices.forEach(function(item){
$scope.total += parseFloat(item.payment);
});
};
$scope.pushPayment = function(item){
if($scope.checked == 'checked'){
return item.payment;
}
};
}]);
If I understand correctly you want a toggle-able check box, If it is checked then you want to copy that invoices amount into the input box below. You could do something similar to below with a combination of ng-model and ng-change
<tr ng-if="invoices.length" ng-repeat="item in invoices | filter: {status:'Unpaid'}">
<td class="first-cell">
<input type="checkbox" ng-model="item.checked" ng-change="select(item)"/>
</td>
<td class="inv-res5">$
<input ng-validate="number" type="number" class="input-mini" ng-model="item.payment" step="0.01"/>
</td>
</tr>
and add the following to your controller
$scope.select = function(item) {
if(item.checked){
item.payment = item.amount;
}
}
What this should do:
You bind the status of the check box to $scope.checked using ng-model
Every time the checkbox status changes ng-change is called, therefore selectInvoice is called.
Select invoice checks whether the checkbox is checked and adjusts the item.payment value accordingly which is bound to the inputs ng-model
See this Plunker for a working example (Note I thinned out the code so its only the bit we're interested in
As an aside, you don't need to have the input box call getTotal when its value changes. Just change the last few lines to:
<td class="inv-res4"><h5>Total to pay:</h5></td>
<td class="inv-res5">{{getTotal() | currency}}</td>
And modify your JavaScript to:
$scope.getTotal = function() {
var total = 0;
$scope.invoices.forEach(function(item){
total += parseFloat(item.payment);
});
return total;
};
It will still be up to date every time Angular 'digests'
The Plunker
The html:
<table class="table table-striped header-fixed" id="invoiceTable">
<thead>
<tr>
<th class="first-cell">Select</th>
<th class="inv-res2">Invoice #</th>
<th class="inv-res3">Bill Date</th>
<th class="inv-res4">Amount</th>
<th class="inv-res5">Amount to Pay</th>
<th class="inv-res6"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in mainCtrl.invoiceList.invoices">
<td class="first-cell"><input type="checkbox" ng-model="item.selected" /></td>
<td class="inv-res2">{{item.invoiceNum}}</td>
<td class="inv-res3">{{item.creationDate}}</td>
<td class="inv-res4" ng-init="invoices.total.amount = invoices.total.amount + item.amount">{{item.amount | currency}}</td>
<td class="inv-res5">$
<input type="text" ng-model="mainCtrl.getAmount(item)"/></td>
</tr>
</tbody>
</table>
<table class="table">
<tbody>
<tr class="totals-row" >
<td colspan="3" class="totals-cell"><h4>Account Balance: <span class="status-error">{{invoices.total.amount | currency }}</span></h4></td>
<td class="inv-res4"><h5>Total to pay:</h5></td>
<td class="inv-res5">{{mainCtrl.getTotalAmount()}}</td>
<td class="inv-res6"></td>
</tr>
</tbody>
</table>
The JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['tempDataStorageService', function(tempDataStorageService) {
var myCtrl = this;
myCtrl.invoiceList = tempDataStorageService;
myCtrl.getAmount = function(item){
return item.selected? item.amount : "";
};
myCtrl.getTotalAmount = function(){
var total = 0;
for(var i = 0; i < tempDataStorageService.invoices.length; i++){
if(tempDataStorageService.invoices[i].selected){
total = total + tempDataStorageService.invoices[i].amount;
}
}
return total;
}
}]);
app.factory('tempDataStorageService', function() {
// The service object
var storage = this;
storage.invoices = [{invoiceNum: 1, creationDate: "1/1/16", amount: 1.50, selected: false},
{invoiceNum: 2, creationDate: "1/2/16", amount: 2.50, selected: false},
{invoiceNum: 2, creationDate: "1/2/16", amount: 2.50, selected: false},
{invoiceNum: 3, creationDate: "1/3/16", amount: 3.50, selected: false},
{invoiceNum: 4, creationDate: "1/4/16", amount: 4.50, selected: false},
{invoiceNum: 5, creationDate: "1/5/16", amount: 5.50, selected: false},
{invoiceNum: 6, creationDate: "1/6/16", amount: 6.50, selected: false},
{invoiceNum: 7, creationDate: "1/7/16", amount: 7.50, selected: false},
{invoiceNum: 8, creationDate: "1/8/16", amount: 8.50, selected: false}];
// return the service object
return storage;
});
That's a way of doing it
Add an attribute amountToPay to your invoices and send the item to the getTotal function:
<input ng-validate="number" type="number" class="input-mini" value="{{pushPayment()}}"
ng-model="item.amountToPay" ng-change="getTotal(item)" step="0.01" /></td>
In your checkbox change the ng-model to item.checked:
<input type="checkbox" ng-checked="item.checked" /></td>
Add this to your getTotal() function:
$scope.getTotal = function(item) {
item.checked = true;
$scope.total = 0;
$scope.invoices.forEach(function(item){
$scope.total += parseFloat(item.payment);
});
};
If you need to populate your input, just modify the amountToPay attribute
Thanks for the assistance, but I think I was overthinking it. I got to work with simply adding:
ng-click="item.payment=item.amount" ng-change="getTotal()"
to the checkbox. I still have to incorporate this into the sum function, but I solved the issue.

Categories