Angularjs, show/hide row's table with ng-repeat - javascript

Sorry, i'm new to ng-repeat. How can i show/hide row table that is using ng-repeat? And the most bottom row is shown if dropdown value is 1.
var i ;
$scope.names = [];
$scope.tmp = [];
for(i=0;i<=10;i++){
$scope.tmp[i] = i;
$scope.names[i] = "name "+ i;
}
$scope.isShow = true
html
<select>
<option ng-repeat="x in tmp">{{x}}</option>
</select>
<table>
<tr ng-show='isShow' ng-repeat="name in names">
<td>{{name}}</td>
</tr>
</table>

May be you must add property isShow for each name in names?
Or create array with visible status for each name.
angular.module('app', [])
.directive('appDir', appDir);
angular.bootstrap(
document.getElementById('root'), ['app']
);
function appDir() {
return {
template: `
<table>
<tr
ng-repeat="name in names"
ng-show="name.isShow"
>
<td>
{{name.title}}
</td>
</tr>
</table>
<select
ng-model="selectedName"
ng-options="x as x for x in tmp"
ng-change="hiddenName()"
>
`,
link: appDirLink
}
}
function appDirLink($scope) {
$scope.names = [];
$scope.tmp = [];
$scope.hiddenName = hiddenName;
for (var i = 0; i < 10; i++) {
$scope.names[i] = {
id: i,
title: 'name_' + i,
isShow: true
};
$scope.tmp[i] = i;
}
function hiddenName() {
$scope.names.map((name, index) => {
name.isShow = (index < $scope.selectedName) ? true : false;
});
}
}
<div id="root">
<app-dir></app-dir>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.min.js"></script>

Related

Knockout array within array

I'm trying to create a simple spreadsheet using Knockout. I'm trying to make each cell observable, so that on changes, I can evaluate the value and calculate accordingly. So if they person enters 6+7 in a cell, I can evaluate and change the value to the total.
However, I can't get each cell to be observable. Maybe I am going about it wrong.
I have tried to create a fiddle, but am now battling to get jquery loaded. So although I can run it within Visual Studio locally, the fiddle is complaining about $. (Any help fixing that would be great).
http://jsfiddle.net/tr9asadp/1/
I generate my observable array like this:
self.RowCount = ko.observable(0);
self.ColumnCount = ko.observable(0);
self.Columns = ko.observableArray([]);
self.Rows = ko.observableArray([]);
self.Refresh = function () {
for (i = 0; i < self.RowCount(); i++) {
var obj = {
data: i + 1,
calculated: i,
rowNum: i,
colNum: 0,
columns: ko.observableArray([])
};
for (j = 0; j < self.ColumnCount(); j++) {
obj.columns.push(ko.observable({
label: self.Letters[j],
value: j + 1,
colIndex: j,
rowIndex: i
}));
}
self.Rows.push(obj);
}
self.ShowSheet(self.RowCount() > 0 && self.ColumnCount() > 0);
I render a table based on the column and rows entered by the user (For now, limited to 5 by 5, as I using an array to convert 1,2,3 (columns) to A,B,C. But that's temporary and will be fixed.
How can I get each cell to be observable so that I can subscribe and fire an event on change?
You don't seem to have made use of cellObject (from your fiddle). If you add objects of type cellObject to the rows and have an observable in there for value you can subscribe to changes on that.
Fixed code:
var cellObject = function() {
var self = this;
self.data = ko.observable();
self.calculated = ko.observable();
self.rowNum = ko.observable(0);
self.colNum = ko.observable(0);
self.rows = ko.observableArray([]);
self.value = ko.observable();
}
function SpreadsheetViewModel() {
var self = this;
self.ShowSheet = ko.observable(false);
self.ShowSheet(false);
self.Letters = ['A', 'B', 'C', 'D', 'E']
self.RowCount = ko.observable(0);
self.ColumnCount = ko.observable(0);
self.Columns = ko.observableArray([]);
self.Rows = ko.observableArray([]);
function valueChanged(newValue) {
console.log("Value changed to " + newValue);
}
self.Refresh = function() {
for (i = 0; i < self.RowCount(); i++) {
var row = {
cells: ko.observableArray([])
};
for (j = 0; j < self.ColumnCount(); j++) {
var cell = new cellObject();
cell.label = self.Letters[j];
cell.data(i + 1);
cell.calculated(i);
cell.rowNum(i);
cell.colNum(j);
cell.value(j + 1);
cell.value.subscribe(valueChanged);
row.cells.push(cell);
}
self.Rows.push(row);
}
self.ShowSheet(self.RowCount() > 0 && self.ColumnCount() > 0);
}
self.Refresh();
}
var vm = new SpreadsheetViewModel();
ko.applyBindings(vm);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="spreadsheetSection">
<div class="row">
<div class="col-xs-3 text-right">No. of Columns</div>
<div class="col-xs-2">
<input type="text" class="form-control" placeholder="Columns" data-bind="value: ColumnCount">
</div>
<div class="col-xs-3 text-right">No. of Rows</div>
<div class="col-xs-2">
<input type="text" class="form-control" placeholder="Rows" data-bind="value: RowCount">
</div>
<div class="col-xs-2">
<button class="btn btn-default" data-bind="click: Refresh">Refresh</button>
</div>
</div>
<div class="row">
<!-- ko if: ShowSheet -->
<table class="table table-bordered table-hover table-striped">
<tbody>
<tr data-bind="foreach: Rows()[0].cells">
<td>
<span data-bind="text: label"></span>
</td>
</tr>
</tbody>
<tbody data-bind="foreach: Rows">
<tr data-bind="foreach: cells">
<td>
<input type="text" class="form-control" data-bind="value: value">
</td>
</tr>
</tbody>
</table>
<!-- /ko -->
</div>
</div>
Fixed fiddle: https://jsfiddle.net/tr9asadp/3/
I used a writableComputable http://knockoutjs.com/documentation/computed-writable.html so that if you type 1 + 1 in one of the cells and tab out, it will change to 2. here is the updated fiddle. http://jsfiddle.net/tr9asadp/5/
function column(label, value, colIndex, rowIndex ){
var self = this;
this.label = ko.observable(label);
this.value = ko.observable(value);
this.colIndex = ko.observable(colIndex);
this.rowIndex = ko.observable(rowIndex);
this.writableValue = ko.pureComputed({
read: function () {
return self.value();
},
write: function (v) {
self.value(eval(v))
},
owner: this
});
}

How have I broken this Todo list in ReactJS code?

An earlier draft of code to handle a Todo list, with fewer features, works:
{
return 0;
}
});
return (
<div id="Todo">
<h1>Todo</h1>
<form onSubmit={that.handleSubmit}>
<table>
{table_rows}
<tfoot>
<textarea name='todo-textarea' id='todo-textarea'
onChange={that.onChange}></textarea><br />
<button>{'Add activity'}</button>
</tfoot>
</table>
</form>
</div>
);
}
});
My present version is getting an InvariantViolation:
react-with-addons.js:20237 Uncaught Error: Invariant Violation: findComponentRoot(..., .0.1.1.0.0:0:0.0:1.0): Unable to find element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>, or <a>, or using non-SVG elements in an parent. Try inspecting the child nodes of the element with React ID ``.
The present code is:
var Todo = React.createClass(
{
mixins: [React.addons.LinkedStateMixin],
getInitialState: function()
{
var result = parse(initial_todo, {
'next_todo_index': 1,
'items': [],
'text': ''
});
return result;
},
handle_change: function(event)
{
var that = this;
var address = jQuery(event.target).attr('data-index').split('.', 2);
var identifier = parseInt(address[0], 10);
for(var candidate = 0; candidate < this.state.next_todo_index;
candidate += 1)
{
if (parseInt(jQuery(this.state.items[candidate]).attr('index'), 10)
=== identifier)
{
(this.state.items[candidate][address[1]] =
!this.state.items[candidate][address[1]]);
save('Todo', this.state);
}
}
that.render();
},
handleSubmit: function(event)
{
event.preventDefault();
var new_item = get_todo_item(this);
new_item.description = this.state.text;
this.state.items.unshift(new_item);
document.getElementById('todo-textarea').value = '';
save('Todo', this.state);
if (!one_shot)
{
one_shot = true;
}
// this.forceUpdate();
// React.render(<Todo />,
// document.getElementById('Todo'));
},
onChange: function(event)
{
this.setState({text: event.target.value});
},
render: function()
{
var that = this;
var table_rows = [];
var display_item_details = function(label, item)
{
var html_id = item.index + '.' + label;
return (
<td className={label} title={label}>
<input onChange={that.handle_change} data-index={html_id}
className={label} type="checkbox"
defaultChecked={item[label]} />
</td>
);
};
var display_item = function(item)
{
var rendered_nodes = [];
if (item['Completed'] || item['Delete'] || item['Invisible'])
{
return '';
}
else
{
for(var index = 0; index < todo_item_names.length;
index += 1)
{
rendered_nodes.push(
display_item_details(todo_item_names[index], item)
);
}
return (
<tr>{rendered_nodes}
<td className="description" dangerouslySetInnerHTML={{__html:
converter.makeHtml(item.description)}} /></tr>
);
}
};
table_rows.push(that.state.items.map(display_item));
table_rows.sort(function(a, b)
{
if (a.index > b.index)
{
return 1;
}
else if (b.index > a.index)
{
return -1;
}
else
{
return 0;
}
});
return (
<div id="Todo">
<h1>Todo</h1>
<form onSubmit={that.handleSubmit}>
<table>
<tbody>
{table_rows}
<tbody>
<tfoot>
<textarea name='todo-textarea' id='todo-textarea'
onChange={that.onChange}></textarea><br />
<button>{'Add activity'}</button>
</tfoot>
</table>
</form>
</div>
);
}
});
How have I broken this?
Do check through your html table structure. Other than the <tbody> fix, the usage of <tfoot> is also invalid markup.
The <tfoot> element can only contain <tr> tags inside.
i.e.
<tfoot>
<tr>
<td>
<textarea name='todo-textarea' id='todo-textarea'
onChange={that.onChange}></textarea><br />
<button>{'Add activity'}</button>
</td>
</tr>
</tfoot>

How do i introduce row and column span in my script?

I'm trying to convert table string (like csv) to html table.
My code works fine with simple table but when it merged row and column it fails. so how do i can use rowspan and column span in the script?
<!DOCTYPE html>
<html ng-app="" ng-controller="myCtrl">
<style>
table, th, td {
border: 1px solid black;
padding:5px;
}
table {
border-collapse: collapse;
margin:10px;
}
</style>
<body>
<button ng-click="processData(allText)">
Display CSV as Data Table
</button>
<div id="divID">
<table>
<tr ng-repeat="x in data">
<td ng-repeat="y in x">{{ y }}</td>
</tr>
</table>
</div>
<div>
<table>
</table>
</div>
JS
<script>
function myCtrl($scope, $http) {
$scope.allText="Series |Wire Range\n (AWG) |"+
"Wire Type |FW |Voltage\n (V) |Current \n (A) |"+
"UG |CA |\nSL-6100 RS#2|26 16, SOL,\n Unprepared |"+
"Cu RS#2|2 RS#2|300 RS#2|7 RS#2|B, D RS#2|"+
"2(105), 4 RS#2|\n24 - 16, STR,\n Unprepared |"+
"\nNominal Strip length: 9 - 10 mm CS#8|"+
"\nEnvironmental - Maximum ambient temperature"+
" rating for CNR: 85 C CS#8|\n";
$scope.processData = function(allText) {
// split content based on new line
var allTextLines = allText.split(/\|\n|\r\n/);
var headers = allTextLines[0].split('|');
var lines = [];
for ( var i = 0; i < allTextLines.length; i++) {
// split content based on comma
var data = allTextLines[i].split('|');
if (data.length == headers.length) {
var temp = [];
for ( var j = 0; j < headers.length; j++) {
temp.push(data[j]);
}
lines.push(temp);
}
};
$scope.data = lines;
};
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>
RS#2 ---indicates rowspan of 2
cs#8 ---indicates colspan of 8
| ---is the dilimiter for cell
|\n ---for new line
and value in $scope.allText is CSV table string
so essentially i should get this table as output-
You can create an object with rows and cols so that you can use that as rowspan and colspan.
Like this
Demo
$scope.processData = function(allText) {
// split content based on new line
var allTextLines = allText.split(/\|\n|\r\n/);
var headers = allTextLines[0].split('|');
var lines = [];
var r,c;
for ( var i = 0; i < allTextLines.length; i++) {
// split content based on comma
var data = allTextLines[i].split('|');
if (data.length == headers.length) {
var temp = [];
for ( var j = 0; j < headers.length; j++) {
if(data[j].indexOf("RS") !== -1) {
r = data[j].split("#").reverse()[0];
}
else {
r = 0;
}
if(data[j].indexOf("CS") !== -1) {
c = data[j].split("#").reverse()[0];
}
else {
c = 0;
}
temp.push({"rows":r,"cols":c,"data":data[j]});
}
lines.push(temp);
}
}
alert(JSON.stringify(lines));
$scope.data = lines;
}
You can add CS to your string and alter conditions as required in this code.
Controller
function myCtrl($scope, $http) {
$scope.allText = "Series |Wire Range\n (AWG) |Wire Type |FW |Voltage\n (V) |Current \n (A) |UG |CA |\nSL-6100 RS#2|26 16, SOL,\n Unprepared |Cu RS#2|2 RS#2|300 RS#2|7 RS#2|B, D RS#2|2(105), 4 RS#2|\n24 - 16, STR,\n Unprepared |\nNominal Strip length: 9 - 10 mm CS#8|\nEnvironmental - Maximum ambient temperature rating for CNR: 85 C CS#8";
$scope.processData = function (allText) {
var table = [];
allText.split(/\|\n|\r\n/).forEach(function (line) {
var tr = [];
line.split('|').forEach(function (cell) {
tr.push({
text: cell.replace(/RS#.*$/, '').replace(/CS#.*$/, ''),
rowspan: (cell + 'RS#1').replace(/^[\S\s]*?RS#(\d*).*$/, '$1'),
colspan: (cell + 'CS#1').replace(/^[\S\s]*?CS#(\d*).*$/, '$1'),
})
})
table.push(tr)
});
$scope.table = table;
};
}
HTML
<table>
<tr ng-repeat="tr in table">
<td ng-repeat="td in tr" ng-attr-colspan="{{td.colspan}}" ng-attr-rowspan="{{td.rowspan}}">{{ td.text }}</td>
</tr>
</table>
Code Snippet
function myCtrl($scope, $http) {
$scope.allText = "Series |Wire Range\n (AWG) |Wire Type |FW |Voltage\n (V) |Current \n (A) |UG |CA |\nSL-6100 RS#2|26 16, SOL,\n Unprepared |Cu RS#2|2 RS#2|300 RS#2|7 RS#2|B, D RS#2|2(105), 4 RS#2|\n24 - 16, STR,\n Unprepared |\nNominal Strip length: 9 - 10 mm CS#8|\nEnvironmental - Maximum ambient temperature rating for CNR: 85 C CS#8";
$scope.processData = function (allText) {
var table = [];
allText.split(/\|\n|\r\n/).forEach(function (line) {
var tr = [];
line.split('|').forEach(function (cell) {
tr.push({
text: cell.replace(/RS#.*$/, '').replace(/CS#.*$/, ''),
rowspan: (cell + 'RS#1').replace(/^[\S\s]*?RS#(\d*).*$/, '$1'),
colspan: (cell + 'CS#1').replace(/^[\S\s]*?CS#(\d*).*$/, '$1'),
})
})
table.push(tr)
});
$scope.table = table;
};
}
angular.module('myApp', [])
.controller('ctrlr', myCtrl)
table, th, td {
border: 1px solid black;
padding: 5px;
}
table {
border-collapse: collapse;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="ctrlr">
<button ng-click="processData(allText)">
Display CSV as Data Table
</button>
<div id="divID">
<table>
<tr ng-repeat="tr in table">
<td ng-repeat="td in tr" ng-attr-colspan="{{td.colspan}}" ng-attr-rowspan="{{td.rowspan}}">{{ td.text }}</td>
</tr>
</table>
</div>
<div>
<table></table>
</div>
</div>
</div>

Populate new Array on ng-repeat

$scope an array consisting Code and Amount on controller. When calculating summary on a function, browser gets Uncaught Error: 10 $digest() iterations reached. Aborting! error which caused from infinite loop (Strange but it is working).
Is there any proper way to combine new Array while ng-repeat without getting infinite loop errors?
Any help would be appreciated
jsFiddle Link
Update: Lines variables are not static, can be added, modified or removed.
jsFiddle Line for Update
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.Lines = [ {Code:'X', Amount:'10'},
{Code:'Y', Amount:'10'},
{Code:'Z', Amount:'20'},
{Code:'Y', Amount:'1'}];
$scope.Sums = function(){
var sums = new Array();
for (var i = 0; i < $scope.Lines.length; i++) {
var added = false;
for (var j = 0; j < sums.length; j++) {
if (sums[j].Code == $scope.Lines[i].Code) {
sums[j].Amount = parseFloat( sums[j].Amount) + parseFloat($scope.Lines[i].Amount);
added = true;
break;
}
}
if (!added) {
sums.push( { Code:$scope.Lines[i].Code, Amount: $scope.Lines[i].Amount } );
}
}
return sums;
}
}
Html:
<div ng-controller="MyCtrl">
<table style="border: 1px solid black;">
<tr ng-repeat="line in Lines">
<td>{{ line.Code }}</td>
<td>{{ line.Amount }}</td>
</tr>
</table>
Summary
<table style="border: 1px solid black;">
<tr ng-repeat="sum in Sums()">
<td>{{ sum.Code }}</td>
<td>{{ sum.Amount }}</td>
</tr>
</table>
</div>
Does this still happen if you do this:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.Lines = [ {Code:'X', Amount:'10'},{Code:'Y', Amount:'10'},
{Code:'Z', Amount:'20'},{Code:'Y', Amount:'1'}];
$scope.Sums = [];
calculate();
var calculate = function(){
$scope.Sums.length = 0;
for (var i = 0; i < $scope.Lines.length; i++) {
var added = false;
for (var j = 0; j < $scope.Sums.length; j++) {
if ($scope.Sums[j].Code == $scope.Lines[i].Code) {
$scope.Sums[j].Amount = parseFloat( $scope.Sums[j].Amount) + parseFloat($scope.Lines[i].Amount);
added = true;
break;
}
}
if (!added) {
$scope.Sums.push( { Code:$scope.Lines[i].Code, Amount: $scope.Lines[i].Amount } );
}
}
}
}
Note that it is important to never create a new array once Sums is watched by angular. Use $scope.Sums.length = 0 instead if you need to empty it.
In your view: <tr ng-repeat="sum in Sums">
As Andre Kreienbring pointed out the problem is because your sum() is returning an object.
I would suggest using filters to accomplish what you need, like so
HTML
<div ng-controller="MyCtrl">
<table style="border: 1px solid black;">
<tr ng-repeat="line in Lines">
<td>{{ line.Code }}</td>
<td>{{ line.Amount }}</td>
</tr>
</table>
Summary
<table style="border: 1px solid black;">
<tr ng-repeat="sum in Lines | unique : 'Code'">
<td>{{ sum.Code }}</td>
<td>{{ Lines | filter: { Code: sum.Code } : true | sum: 'Amount' }}</td>
</tr>
</table>
</div>
Script
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.Lines = [ {Code:'X', Amount:'10'},{Code:'Y', Amount:'10'},
{Code:'Z', Amount:'20'},{Code:'Y', Amount:'1'}];
}
myApp.filter('unique', function() {
return function(input, key) {
var unique = {};
var uniqueList = [];
for(var i = 0; i < input.length; i++){
if(typeof unique[input[i][key]] == "undefined"){
unique[input[i][key]] = "";
uniqueList.push(input[i]);
}
}
return uniqueList;
};
});
myApp.filter('sum', function() {
return function(input, key) {
var sum = 0;
for(var i = 0; i < input.length; i++){
sum += Number(input[i][key]);
}
return sum;
};
});
The unique filter is from https://stackoverflow.com/a/18382680/360067
Fiddle - http://jsfiddle.net/34od99sz/
I'd rather put a $watch on $scope.Lines which will create an array and populate it as $scope.sums such that ng-repeat doesn't have to call the method again and again. See Fiddle
Edit (added missing parameter for deep watching):
Fiddle
if I am not mistaken in the line
for (var j = 0; j < sums.length; j++)
you try to take the length of sums whitch is a new array. it has no length though. Also why do you use
var sums = new Array();
to initialize the array and not
var sums = [];

AngularJS sum of rows ng-repeat

I add dynamically rows in my table with ng-repeat, coming from an array.
Now I want to get the sum of all sums per row (group.sum * group.perc / 100.0). I need it in a variable because I need this value for further calculations. Thank you
HTML
<tr ng-repeat="group in groupsArr">
<td class="total-rows" ng-model="taxes">{{group.sum * group.perc / 100.0 | currency :""}}</td>
</tr>
SCRIPT
var taxTotals = 0;
var taxTotals =
for (i=0; i<group.length; i++) {
taxTotal = taxTotal + group[i].taxes;
};
console.log(taxTotals);
};
Create a Filter:
app.filter('sumFilter', function() {
return function(groups) {
var taxTotals = 0;
for (i=0; i<groups.length; i++) {
taxTotal = taxTotal + groups[i].taxes;
};
return taxTotals;
};
});
Use the $filter service:
app.controller('myController', function($scope, $filter) {
$scope.groups = [...];
var taxTotals = $filter('sumFilter')($scope.groups);
console.log(taxTotals);
});
Use it in your HTML:
<tr ng-repeat="group in groupsArr">
<td class="total-rows" ng-model="taxes">{{group.sum * group.perc / 100.0 | currency :""}} </td>
</tr>
<tr>
<b> Tax Totals: </b> {{ groupsArr | sumFilter | currency }}
</tr>
An addition for best answer... I am using filter in my very huge table, so it is how to implement with dynamic filters.
THE FILTER
app.filter('sumStatusFilter', function(){
return function (items, filtersStatus, filterLocations){
var filtered = [];
var filtered1 = [];
var total = 0;
if (typeof filtersStatus != 'undefined') {
angular.forEach(items, function(item) {
for(i = 0; i < filtersStatus.length; i ++){
if(filtersStatus[i] == item.status_message)
filtered.push(item);
}
});
}
if (typeof filterLocations != 'undefined') {
angular.forEach(filtered, function(item) {
for(i = 0; i < filterLocations.length; i ++){
if(filterLocations[i] == item.office_location)
filtered1.push(item);
}
});
filtered = [];
filtered = filtered1;
}
if (filtered.length == 0) {
filtered = this.jobs
}
angular.forEach(filtered, function(value, key){
total += value.restoration_reserve
});
return total;
}
});
in HTML
<tr><td>Total: {{ report_controller.items | sumStatusFilter:report_controller.status_message_selections:report_controller.office_selections | currency }}</td></tr>
UPDATE AFTER ANSWER coming from pixelbits
Thanks to pixelbits. Here is my filter, which works perfect within the view.
HTML
<tr ng-repeat="group in groupsArr">
<td class="total-rows" ng-model="taxes">{{group.sum * group.perc / 100.0 | currency :""}} </td>
</tr>
<tr>
<b> Tax Totals: </b> {{ groupsArr | sumFilter | currency }}
</tr>
Filter
angular.module('App.filters', []).filter('sumFilter', [function () {
// filter for tax sum
return function(groups, lenght) {
var taxTotal = 0;
for (i=0; i < groups.length; i++) {
taxTotal = taxTotal + ((groups[i].perc * groups[i].sum) / 100);
};
return taxTotal;
};
}]);
If I want to access from my controller, it doesn´t work: I cannot get the variable taxTotals *Cannot read property 'length' of undefined
As mentioned, in the view it works.
Filter Service
var taxTotal = $filter('sumFilter')($scope.groups);
console.log(taxTotal);
Or use Map Reduce!
Controller
$scope.mappers = {
tax: function(m){
return group.sum * group.perc / 100.0;
}
}
$scope.sum = function(m){
if($scope.groupsArr.length == 0) return;
return $scope.groupsArr.map(m).reduce(function(p, c){
return p + c;
}) || 0;
};
HTML
<tr ng-repeat="group in groupsArr">
<td class="total-rows" ng-model="taxes">{{group.sum * group.perc / 100.0 | currency :""}} </td>
</tr>
<tr>
<b> Tax Totals: </b> {{ sum(mappers.tax) }}
</tr>

Categories

Resources