dynamic result counter during search - javascript

in this code snippet you can see a little overview which displays some sample data on several table pages. The pagination and everything else works fine but if I type something into my search, the count of the results changes but the counter at the top stays the same. It also should change dynamically if I restrict the results with the search. So for example if I type "item_44" it should display 1 - 1 of 1 because there is just 1 entry.
I would be glad if someone has an idea how to fix the issue.
Here is the working example.
var myApp = angular.module('myApp', []);
myApp.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
var vm = this;
//vm.currentActive = sessionService.getState();
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.data = [];
$scope.firstItem = 0;
$scope.lastItem = $scope.firstItem + $scope.pageSize;
$scope.numberOfPages = function() {
return Math.ceil($scope.data.length / $scope.pageSize);
}
for (var i = 0; i < 45; i++) {
$scope.data.push("Item " + i);
}
$scope.nextPage = function() {
if ($scope.currentPage >= $scope.data.length / $scope.pageSize - 1) {
} else {
$scope.currentPage = $scope.currentPage + 1;
$scope.firstItem = $scope.firstItem + $scope.pageSize;
if ($scope.firstItem + $scope.pageSize > $scope.data.length) {
$scope.lastItem = $scope.data.length;
} else {
$scope.lastItem = $scope.firstItem + $scope.pageSize;
}
}
}
$scope.prevPage = function() {
if ($scope.currentPage === 0) {
} else {
$scope.currentPage = $scope.currentPage - 1;
$scope.firstItem = $scope.firstItem - $scope.pageSize;
$scope.lastItem = $scope.firstItem + $scope.pageSize;
}
}
}
.name-row {
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<div ng-controller="MyCtrl" class="wrapper">
<div class="view-navigation">
<span ng-click="prevPage()" id="hoverfinger"><i class="material-icons">skip_previous</i></span>
<span class="counter">{{firstItem +1}} - {{lastItem}} of {{data.length}}</span>
<span ng-click="nextPage()" id="hoverfinger"><i class="material-icons" >skip_next</i></span>
</div>
<br>
<span ng-click="nextPage()" id="hoverfinger"><i class="material-icons" >search</i></span>
<input type="text" ng-model="search" placeholder="search..." />
<table border="1">
<tr>
<th class="name-row">Name</th>
<th class="info-row">Info</th>
</tr>
<tr ng-repeat="item in data | filter:search | startFrom:currentPage*pageSize | limitTo:pageSize">
<td>{{item}}</td>
<td>more info...
</td>
</tr>
</table>
</div>
Somehow the snippet doesn't work in the StackOverflow site.

Try this , its working.
HTML
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<div ng-controller="MyCtrl">
<div class="view-navigation">
<span ng-disabled="currentPage == 0" ng-click="back()" id="hoverfinger"><i class="material-icons">skip_previous</i></span>
<span class="counter">{{currentPage+1}} - {{numberOfPages()}} von {{getDataLength()}}</span>
<span ng-disabled="currentPage >= getData().length/pageSize - 1" ng-click="forward()" id="hoverfinger"><i class="material-icons" >skip_next</i></span>
</div>
<br>
<span ng-click="nextPage()" id="hoverfinger"><i class="material-icons" >skip_next</i></span><input type="text" ng-model="q" placeholder="search..."/>
<table border="1">
<tr>
<th>Status</th>
<th>Name</th>
<th>Info</th>
</tr>
<tr ng-repeat="item in s=( data | filter:q | startFrom:currentPage*pageSize | limitTo:pageSize)">
<td><span><i class="material-icons" style="color: #8AC65B">check_circle</i></span></td>
<td>{{item}}</td>
<td>more info...</td>
</tr>
</table>
</div>
javascript
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', ['$scope', '$filter', function ($scope, $filter) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.data = [];
$scope.q = '';
$scope.getData = function () {
return $filter('filter')($scope.data, $scope.q)
}
$scope.getDataLength = function () {
var arr = [];
arr = $filter('filter')($scope.data, $scope.q)
return arr.length;
}
$scope.numberOfPages=function(){
return Math.ceil($scope.getData().length/$scope.pageSize);
}
$scope.back = function(){
if($scope.currentPage == 0){return}else{
$scope.currentPage=$scope.currentPage-1;}
}
$scope.forward = function(){
var val = $scope.numberOfPages();
if(val == ($scope.currentPage+1)){
alert('val');
}
else {
$scope.currentPage+=1;}
}
for (var i=0; i<45; i++) {
$scope.data.push("Item "+i);
}
}]);
myApp.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});

I am sure Please Change below code according in your code working fine.
var myApp = angular.module('myApp',[]);
myApp.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
var vm = this;
//vm.currentActive = sessionService.getState();
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.data = [];
$scope.firstItem = 0;
$scope.lastItem = $scope.firstItem + $scope.pageSize;
$scope.numberOfPages=function(){
return Math.ceil($scope.data.length/$scope.pageSize);
}
for (var i=0; i<45; i++) {
$scope.data.push("Item "+i);
}
$scope.nextPage = function(){
if($scope.currentPage >= $scope.data.length/$scope.pageSize - 1){
}
else{
$scope.currentPage = $scope.currentPage + 1;
$scope.firstItem = $scope.firstItem + $scope.pageSize;
if($scope.firstItem + $scope.pageSize > $scope.data.length){
$scope.lastItem = $scope.data.length;
}
else{
$scope.lastItem = $scope.firstItem + $scope.pageSize;
}
}
}
$scope.prevPage = function(){
if($scope.currentPage === 0){
}
else{
$scope.currentPage = $scope.currentPage - 1;
$scope.firstItem = $scope.firstItem - $scope.pageSize;
$scope.lastItem = $scope.firstItem + $scope.pageSize;
}
}
}
<html ng-app='myApp'>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head><body ng-controller="MyCtrl" >
<div class="wrapper">
<div class="view-navigation">
<span ng-click="prevPage()" id="hoverfinger"><i class="material-icons">skip_previous</i></span>
<span class="counter">{{firstItem +1}} - {{griddata.length}} of {{data.length}}</span>
<span ng-click="nextPage()" id="hoverfinger"><i class="material-icons" >skip_next</i></span>
</div>
<br>
<span><i class="material-icons" >search</i></span><input type="text" ng-model="search" placeholder="search..."/>
<table border="1">
<tr>
<th class="name-row">Name</th>
<th class="info-row">Info</th>
</tr>
<tr ng-repeat="item in griddata=(data | filter:search | startFrom:currentPage*pageSize | limitTo:pageSize)">
<td>{{item}}</td>
<td>more info...</td>
</tr>
</table>
</div>
</body>
</html>

Related

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

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>

Angular 1 Error: [ng:areq] - Controller inside Controller

I'm trying to use angular rating from this http://plnkr.co/edit/kFKejRU0G2wmkD7GlNdH?p=preview
Here is my Angular code:
var ProfileApp = angular.module('ProfileApp', ['ui.bootstrap']);
ProfileApp.controller('getprofile', function($scope, $http) {
//Some codes are here
})
var RatingDemoCtrl = function ($scope) {
$scope.myRate = 0;
$scope.submit = function() {
console.log($scope.percent) ; //null
}
$scope.rate = 1;
$scope.max = 5;
$scope.isReadonly = false;
$scope.percent = 20;
$scope.hoveringOver = function(value,object) {
console.log('hoveringOver', value);
$scope.overStar = value;
$scope.percent = (100 * $scope.overStar) / $scope.max;
};
$scope.hoveringLeave = function(rate) {
console.log('hoveringLeave', $scope.rate);
$scope.percent = (100 * $scope.rate) / $scope.max;
};
};
Above code is used for Rating.
Here is the html code.
<body id="home" ng-app="ProfileApp">
<div ng-controller="getprofile">
//Some html codes
<div ng-controller="RatingDemoCtrl" class="well well-small">
<form class="Scroller-Container" ng-submit="submit()" ></form>
<rating value="rate" max="max" readonly="isReadonly" on-hover="hoveringOver(value)" on-leave="hoveringLeave(rate)" ></rating>
<span class="badge" ng-class="{'badge-warning': percent<30, 'badge-info': percent>=30 && percent<70, 'badge-success': percent>=70}" ng-show="overStar && !isReadonly">{{percent}}%</span>
<input type="submit" id="submit" value="Submit" />
</form>
<pre>{{percent}}</pre>
</div>
As you can see I have nested controller and this is giving me error Error: [ng:areq].
What can be done now? Is there any way I can fix it?
Update
After using the code of saj now I am getting error.
angular.min.js:101 Error: [ngRepeat:dupes] http://errors.angularjs.org/1.3.2/ngRepeat/dupes?p0=r%20in%20range&p1=object%3A10&p2=%7B%22stateOn%22%3Anull%2C%22stateOff%22%3Anull%7D
No star is vising. I inspect the code and codes are below.
<div ng-controller="RatingDemoCtrl" class="well well-small ng-scope">
<form class="Scroller-Container ng-pristine ng-valid" ng-submit="submits()"></form>
<span ng-mouseleave="reset()" value="rate" max="max" readonly="readonly" on-hover="hoveringOver(value)" on-leave="hoveringLeave(rate)" class="ng-isolate-scope">
<!-- ngRepeat: r in range -->
</span>
<span class="badge ng-binding badge-warning ng-hide" ng-class="{'badge-warning': percent<30, 'badge-info': percent>=30 && percent<70, 'badge-success': percent>=70}" ng-show="overStar && !isReadonly">20%</span>
<input type="submit" id="submit" value="Submit">
<pre class="ng-binding">20</pre>
</div>
You just need to separate out 'RatingDemoCtrl' controller
app.controller('RatingDemoCtrl', function($scope) {
$scope.myRate = 0;
$scope.submit = function() {
console.log($scope.percent); //null
}
$scope.rate = 1;
$scope.max = 5;
$scope.isReadonly = false;
$scope.percent = 20;
$scope.hoveringOver = function(value, object) {
console.log('hoveringOver', value);
$scope.overStar = value;
$scope.percent = (100 * $scope.overStar) / $scope.max;
};
$scope.hoveringLeave = function(rate) {
console.log('hoveringLeave', $scope.rate);
$scope.percent = (100 * $scope.rate) / $scope.max;
};
});
WORKING DEMO

How to apply multiple filters with pagination in Angular JS?

I am trying to apply multiple filters with pagination in Angular JS i am able to paginate the results with one filter but whenever there is multiple filters i am unable do it OR is performing among two filters instead of AND please help me to achieve this any help will be greatly appreciated. here is my code.
Here is my index.html
<html xmlns:ng="http://angularjs.org" ng-app lang="en">
<head>
<meta charset="utf-8">
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap.no-icons.min.css" rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/font-awesome/2.0/css/font-awesome.css" rel="stylesheet">
<script src="http://code.angularjs.org/1.1.0/angular.min.js"></script>
</head>
<body>
</div>
<div ng-controller="ctrlRead">
<div class="input-append">
<input type="text" ng-model="name" ng-change="nameSearch()" class="input-large search-query" placeholder="Search Name">
<input type="text" ng-model="country" ng-change="countrySearch()" class="input-large search-query" placeholder="Search Name">
<span class="add-on"><i class="icon-search"></i></span>
</div>
<div class="pagination pull-right">
<ul>
<li ng-class="{disabled: currentPage == 0}">
<a href ng-click="prevPage()">« Prev</a>
</li>
<li ng-repeat="n in range(pagedItems.length)"
ng-class="{active: n == currentPage}"
ng-click="setPage()">
<a href ng-bind="n + 1">1</a>
</li>
<li ng-class="{disabled: currentPage == pagedItems.length - 1}">
<a href ng-click="nextPage()">Next »</a>
</li>
</ul>
</div>
</div>
</body>
</html>
And here is my script.
function ctrlRead($scope, $filter) {
// init
$scope.sortingOrder = sortingOrder;
$scope.reverse = false;
$scope.filteredItems = [];
$scope.groupedItems = [];
$scope.itemsPerPage = 5;
$scope.pagedItems = [];
$scope.currentPage = 0;
$scope.items = [
{"id":"1","name":"John","country":"usa"},
{"id":"2","name":"Peter",,"country":"London"}];
// init the filtered items
$scope.nameSearch = function () {
$scope.filteredItems = $filter('filter')($scope.items, function (item) {
if(item.name.includes($scope.name)){
return true;
}
});
$scope.countrySearch = function () {
$scope.filteredItems = $filter('filter')($scope.items, function (item) {
if(item.country.includes($scope.country)){
return true;
}
});
$scope.currentPage = 0;
// now group by pages
$scope.groupToPages();
};
// calculate page in place
$scope.groupToPages = function () {
$scope.pagedItems = [];
for (var i = 0; i < $scope.filteredItems.length; i++) {
if (i % $scope.itemsPerPage === 0) {
$scope.pagedItems[Math.floor(i / $scope.itemsPerPage)] = [ $scope.filteredItems[i] ];
} else {
$scope.pagedItems[Math.floor(i / $scope.itemsPerPage)].push($scope.filteredItems[i]);
}
}
};
$scope.range = function (start, end) {
var ret = [];
if (!end) {
end = start;
start = 0;
}
for (var i = start; i < end; i++) {
ret.push(i);
}
return ret;
};
$scope.prevPage = function () {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.nextPage = function () {
if ($scope.currentPage < $scope.pagedItems.length - 1) {
$scope.currentPage++;
}
};
$scope.setPage = function () {
$scope.currentPage = this.n;
};
// functions have been describe process the data for display
$scope.search();
};
ctrlRead.$inject = ['$scope', '$filter'];
Hope this will help you, I am using standard filter and 2 other drop downs through which I am doing filter in table.
HTML Code
<div>
<label>Associated Products:</label>
<div class="row">
<div class="col-md-6">
<div class="col-md-4 custom-select">
<div class="custom-select-text">{{selected}}</div>
<select class="form-control select-area c-corporate-contact-us-from-select-country country-lang-select" data-widget="custom-select"
(change)="onSelectProductLine($event)" [(ngModel)]="selected">
<option value="0">Select a product line</option>
<option *ngFor="let ProductLine of productLines" value={{ProductLine.categoryId}}>
{{ProductLine.title}}
</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="col-md-4 custom-select" *ngIf="edited">
<div class="custom-select-text">{{selectedProduct}}</div>
<select class="form-control select-area c-corporate-contact-us-from-select-country country-lang-select" data-widget="custom-select"
(change)="onSelectProduct($event)" [(ngModel)]="selectedProduct">
<option value="0">Select a product</option>
<option *ngFor="let Product of products" value={{Product.categoryId}}>
{{Product.title}}
</option>
</select>
</div>
</div>
</div>
</div>
<div class="example-header">
<mat-form-field>
<input matInput (page)="changePage($event)" (keyup)="applyFilter($event.target.value)" placeholder="Search Products based on Product Numbers or Description or Associate Products">
</mat-form-field>
</div>
JS Code
onSelectProductLine(args) {
if (args.target.value != 0)
this.edited = true;
else
this.edited = false;
this.dataservice.getProduct(args.target.value).subscribe(res => this.products = res);
this.selected = args.target.options[args.target.selectedIndex].text;
this.applyFilterTopLevelProduct(this.selected);
}
onSelectProduct(args) {
this.selectedProduct = args.target.options[args.target.selectedIndex].text;
this.applyFilterSecondLevelProduct(this.selectedProduct);
}
applyFilter(filterValue: string) {
debugger;
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.productNumbers + data.title + data.associatedProducts).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
applyFilterTopLevelProduct(filterValue: string) {
debugger;
if (filterValue == "Select a product line")
filterValue = "";
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.toplevelProduct).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
applyFilterSecondLevelProduct(filterValue: string) {
if (filterValue == "Select a product") {
filterValue = this.selected;
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.toplevelProduct).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
else {
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.associatedProducts).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
}

How can I show next 15 items in ng-repeat?

I am currently using angular ng-repeat.
When a user clicks a button that says "Next 15", I would like to show next 15 items.
I don't want to pop items from array, I would just like to hide first 15, and limit show to just the next 15.
Also, when the user clicks "Prev 15", I would like to show just the previous 15 items.
Here is what I have so far:
HTML:
<div ng-controller="ctrlIndex as vm">
<ul ng-repeat=" item in vm.items | limitTo: 15 * vm.page
| limitTo: 15 * vm.page < count ? limitTo: 15 * vm.page : 15 - (15 * vm.page - count)"/>
<li>{{ item }}</li>
</ul>
<div><button ng-click="vm.next()">Next 15</button></div>
<div><button ng-click="vm.back()">Prev 15</button></div>
Javascript:
var app = angular.module('app', []);
3app.controller('ctrlIndex', function(){
var vm = this;
vm.numRecords = 15;
vm.page = 1;
vm.items = []
for (var i = 0; i < 1000000; ++i) {
vm.items.push('item : ' + i);
}
vm.next = function(){
vm.page = vm.page + 1;
};
vm.back = function(){
vm.page = vm.page - 1;
};
});
Here you go - Plunker
Markup
<body ng-app="app">
<div ng-controller="ctrlIndex as vm">
<ul ng-repeat="item in vm.items track by $index"
ng-show="(($index < (vm.page * vm.numRecords)) && ($index >= ((vm.page - 1) * vm.numRecords)))">
<li>{{ item }}</li>
</ul>
<div><button ng-click="vm.next()">Next 15</button></div>
<div><button ng-click="vm.back()">Prev 15</button></div>
</div>
</body>
Something like the following will allow you to keep your view tidy and your logic testable:
// controller
var vm = this;
vm.numRecords = 15;
vm.page = 0;
vm.items = [];
vm.data = {};
vm.data.shownItems = [];
vm.limit = 100;
vm.maxPages = Math.floor(vm.limit / vm.numRecords);
for (var i = 0; i < vm.limit; ++i) {
vm.items.push('item : ' + i);
}
vm.data.shownItems = vm.items.slice(0, this.numRecords);
vm.next = function() {
if (vm.page >= vm.maxPages) {
return
}
vm.page += 1;
var begin = vm.page * vm.numRecords;
var end = begin + vm.numRecords;
vm.data.shownItems = vm.items.slice(begin, end);
};
vm.back = function() {
if (vm.page <= 0) {
return
}
vm.page -= 1;
var begin = vm.page * vm.numRecords;
var end = begin + vm.numRecords;
vm.data.shownItems = vm.items.slice(begin, end);
};
// view
<ul ng-repeat="item in vm.data.shownItems">
<li>{{ item }}</li>
</ul>
Plunker

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