sum of values in a list using angular way - angularjs

I have a short piece of sample here where myself trying to get total of values in angular way as,
<div id="app" ng-app="myApp" ng-controller="myCtrl" ng-init="total = 0">
<ul>
<li ng-repeat="x in myarr" > {{x.val}}
<span ng-if="$last">, Total - {{total = total+x.val}}</span>
</li>
</ul>
</div>
But total is incorrect. How can it be achieved?
EDIT: Myself trying to get total within the ng-repeat loop beside last element. There is an accepted answer in this question and below answer also work in same logic. But In that method, the function getTotal() will call myarr.length times and each time the array loops in controller right? So as per example in the question, array will loop completely 6 times (myarr.length + once in ng-repeat ie, 5+1). Do i wrong?

Try this method, no function used in controller , using ng-init in ng-repeat
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.myarr = [{id: 1, val: 500},{id: 2,val: 300},{id: 3,val: 200},{id: 4,val: 600},{id: 5,val: 100}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="app" ng-app="myApp" ng-controller="myCtrl" ng-init="total=0">
<ul >
<li ng-repeat="x in myarr" ng-init="$parent.total = $parent.total + (x.val)"> {{x.val}}
<span ng-if="$last">{{total}}</span>
</li>
</ul>
</div>
Another method ,
Use array.reduce to add sum of array Link
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.myarr = [{id: 1, val: 500},{id: 2,val: 300},{id: 3,val: 200},{id: 4,val: 600},{id: 5,val: 100}];
$scope.addTotal = function(){
var sum = $scope.myarr.reduce($scope.add);
return sum.val;
}
$scope.add = function(a,b){
return {val:a.val + b.val};
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="app" ng-app="myApp" ng-controller="myCtrl" ng-init="total=0">
<ul >
<li ng-repeat="x in myarr" > {{x.val}}
<span ng-if="$last">{{addTotal()}}</span>
</li>
</ul>
</div>

Try doing all calculations in angular controller itself and storing it in varaible. But if you are worried about values in array constantly changing you can also use a calcTotal function in your controller. Also ng-repeat should be on li and not ul.
<div id="app" ng-app="myApp" ng-controller="myCtrl" ng-init="total = 0">
<ul >
<li ng-repeat="x in myarr"> {{x.val}}
<span ng-if="$last">, Total - {{getTotal()}} or {{totalValue}}</span>
</li>
</ul>
</div>
Your controller will be like
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.myarr = [{id: 1, val: 500},{id: 2,val: 300},{id: 3,val: 200},{id: 4,val: 600},{id: 5,val: 100}];
//first approach
$scope.totalValue = 0;
for(i=0;i<$scope.myarr.length;i++){
if($scope.myarr[i] && $scope.myarr[i].val)
$scope.totalValue+=$scope.myarr[i].val;
}
//OR
//second approach
$scope.getTotal = function(){
var total = 0;
for(i=0;i<$scope.myarr.length;i++){
if($scope.myarr[i] && $scope.myarr[i].val)
total+=$scope.myarr[i].val;
}
return total;
}
});
If you are using variable approach, you will have to explicitly calculate $scope.getTotal everytime the array values change. By the function approach it will happen itself, but binding functions on UI is little expensive as they keep re-calculating on every digest cycle.

You can use angular.forEach to loop and have you total count.
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.total = 0;
$scope.myarr = [{id: 1, val: 500},{id: 2,val: 300},{id: 3,val: 200},{id: 4,val: 600},{id: 5,val: 100}];
angular.forEach($scope.myarr, function(value){$scope.total+=value.val});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="app" ng-app="myApp" ng-controller="myCtrl">
<ul >
<li ng-repeat="x in myarr" > {{x.val}}
<span ng-if="$last">{{total}}</span>
</li>
</ul>
</div>

Related

angularjs pass index through directive

I need help with this code.
<ul ng-init="round = 'round'">
<li ng-repeat="mesa in mesas" ng-click="selected($index)">
<div id="{{round}}"> </div>
MESA {{mesa}}
</li>
</ul>
$scope.selected = function ($index){
$scope.index.round = 'round1';
}
I need that only the li that is being clicked to change the css name, but instead it change all of the li's that I have listed.
You're initializing the variable round outside of the repeat loop, so the expression {{round}} will always point to that singular, shared variable. If you update it once, it updates for all children of the ng-repeat.
If I understand your question, you're trying to change the CSS class for the div inside the repeat, correct? What you can do in that case is store the selected index on the controller's scope, and check that value against the index inside the loop
<ul>
<li ng-repeat="mesa in mesas" ng-click="select($index)">
<div class="round1" ng-if="selectedIndex === $index"> </div>
<div class="round" ng-if="selectedIndex !== $index"> </div>
MESA {{mesa}}
</li>
</ul>
$scope.select = function ($index){
$scope.selectedIndex = $index;
}
You could also use ng-class instead of ng-if depending on how your CSS is structured, but the idea is the same.
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<style type="text/css">
.round {
background: green;
}
.round1 {
background: blue;
}
</style>
</head>
<body ng-controller="controller">
<ul>
<li ng-repeat="mesa in mesas" ng-click="selected($index)" ng-class="[index[$index].round]">
<div id="{{ index[$index].id }}"> </div>
MESA {{ mesa }}
</li>
</ul>
</html>
<script type="text/javascript">
angular.module('app', [])
.controller('controller', controller);
controller.$inject = ['$scope'];
function controller($scope) {
$scope.mesas = ['1', '2', '3'];
$scope.index = [{
id: '1',
round: 'round'
}, {
id: '2',
round: 'round'
}, {
id: '3',
round: 'round'
}];
$scope.selected = function($index) {
$scope.index[$index].round = $scope.index[$index].round === 'round' ? 'round1' : 'round';
}
}
</script>
I think is what u looking for¿?

how do i write ng-repeat for this in my html code

for(var i=0;i<a.length;i++){
$scope.inputs=[
{name:a[i],value:b[i]}
];
}
this is my Javascript code i want to know how to write (ng-repeat) for arrays
Your JS is invalid, will produce length 1 array. Replace it with this:
$scope.inputs=[];
for(var i=0;i<a.length;i++){// be sure that a.length >=b.length
$scope.inputs.push({name:a[i],value:b[i]}); // push will add new entry to your inputs array.
}
The you can use it in ng-repeat:
<div ng-repeat="entry in inputs"> {{entry.name}} : {{entry.value}} </div>
You don't write loops surrounding a global variable. You leave the variable by itself and then you call the loop. Later you just use the global variable in the html code.
I made a cool snippet so you understand how it works:
angular.module('demo', [])
.controller('Ctrl', ['$scope', function ($scope) {
$scope.inputs = [];
var a = ['name1', 'name2', 'name3'];
var b = [133,233,456];
//this code has to be called somewhere else. It might be part of a function.
for(var i=0; i < a.length; i++){
$scope.inputs.push( {name:a[i],value:b[i]} );
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="Ctrl">
<ul>
<li ng-repeat="item in inputs">
<input ng-model="item.name"/>
</li>
</ul>
<!--This is only to display the content of $scope.inputs -->
<pre>{{inputs | json}}</pre>
</div>
</div>
If you have an array in your controller, with a scope that is visible in your html
angular.module('appName').controller('mainCtrl', mainCtrl);
function mainCtrl($scope) {
$scope.inputs = [
key: value,
...
];
}
In your html you would use ng-repeat within the scope of the controller. You can use the ng-repeat directive on several different html tags, such as <ul> lists, a div, select dropdowns and more
<div ng-controller="mainCtrl">
<ul>
<li ng-repeat="item in inputs">{{item.key}} <!-- Prints 'value' --></li>
</ul>
</div>

How to show the ID of array objects?

I was wondering how to print ids of items inside an array.
I have and array called localData, with a list of objects inside. Every object is a mini array of 3 strings.
In my ng-repeat when i set {{items in array}} it prints the content and not the id. How can i print only ids?
localData = {"-KRFLxEmRoS7M9gKDXVE":{"postBody":"1) remove lag 2) add animations",
"postTitle":"Top Title $$$","userName":"[Admin]"},
"-KRFM6Jm2wQemtl878Ur":"postBody":"Annanana","postTitle":"Ananaj",
"userName":"[Admin]"},"-KRFM7rcEe5K5PXkb29v":{"postBody":"Abshhsua","postTitle":"Ababjsjs","userName":"[Admin]"},
"-KRFM96LtmaXRTnUXJoV":{"postBody":"Gabshsysus","postTitle":"Bshshshshs","userName":"[Admin]"},
"-KRFMAnqecr85xUcOCuw":{"postBody":"Sbsbshshsusudu","postTitle":"Ushhshshs","userName":"[Admin]"},
"-KRFMCkO3JdhA_0MlwwM":{"postBody":"Hshshshs","postTitle":"Sjjsjsjs","userName":"[Admin]"},
"-KRFMLtDJsO0fGYA9JEO":{"postBody":"Fake",
"postTitle":"OMG EPICCCCCCOOOO","userName":"[Admin]"},
"-KRFMQBwIbK6s5lVMlbW":{"postBody":"Asdrobololo","postTitle":"Asdrubale","userName":"[Admin]"},
"-KRI7TVGM0U5emvwD0i7":{"postBody":"Htrsdvgh","postTitle":"Uutfcbuj","userName":"[Admin]"},"-KRITPhL8m-qCCO9y4vY":
{"postBody":"Iiiiiiiwwwwww","postTitle":"Jjjdhd","userName":"[Admin]"}}
angular.module('myapp', [])
.controller('PostsCtrl', function($scope) {
var object={"nm_questionario":{"isEmpty":"MSGE1 - Nome do Questionário"},"ds_questionario":{"isEmpty":"MSGE1 - Descrição do Questionário"},"dt_inicio_vigencia":{"isEmpty":"MSGE1 - Data de Vigência"}};
$scope.items = [];
angular.forEach(object, function (value, key) {
$scope.items.push(key);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="PostsCtrl">
<div ng-repeat="item in items">
{{item}}
</div>
</div>
Store the local data like below to get the id easily. Try this below.
angular.module('myapp', [])
.controller('PostsCtrl', function($scope) {
var accountservice=[{"id":"1","title":"Savings Account","services":[{"types":"ATM card request"},{"types":"loan request"}]},
{"id":"2","title":"Current Account","services":[{"types":"cheque book request"},{"types":"ATM card request"}]},
{"id":"3","title":"Demat Account","services":[{"types":"loan request"},{"types":"ATM card request"}]}];
$scope.accountservices = accountservice;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="PostsCtrl">
<div ng-repeat="(key,value) in accountservices">
<p>{{value.id}}</p>
<ul><li ng-repeat="account in value.services">{{account.types}}</li></ul>
</div>
</div>

How to sort array of integers in angularjs using custom filters??

here is my code , i dont know what mistake i am doing??? Is there a built in filter or function to sort array of integers or numbers??
<body data-ng-app="app" data-ng-controller="controller1" >
<div class="container">
<div class="row">
<input type="text" ng-model="searchbox" />
<li ng-repeat="num in numbers|filter:searchbox|orderBy:number">
{{num}}
</li>
</div>
</div>
<script type="text/javascript">
var app=angular.module('app', []).controller('controller1', ['$scope', function($scope){
$scope.numbers=[10,8,6,7];
$scope.number=function(data)
{
return data.sort();
}
}
]);
</script>
</body>
Check out this answer orderBy array item value in Angular ng-repeat
This means that you can do something like this:
app.controller('ctrl', ['$scope', function($scope){
$scope.numbers = [10,8,6,7];
$scope.identity = angular.identity;
}]);
And
<li ng-repeat="num in numbers | orderBy:identity">
{{num}}
</li>

binding 3 arrays data using angular js

I'm binding the array data using reference $index but i'm getting arrays in group2 and value
I need like this:
grp1
abc,def
value1,value2
grp2
adf,cdf
value3,value4
But Im getting :
grp1
["abc","def"]
[["value1","value2"]]
grp2
["adf","cdf"]
[["value3","value4"]]
Below code i tried
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body>
<div ng-app ng-controller="ListCtrl" ng-cloak>
<ul ng-repeat="group in group1">
<li>{{group}}</li>
<li>{{group2[$index]}}</li>
<li>{{value[$index]}}</li>
</ul>
</div>
</body>
</html>
Script:
function ListCtrl($scope) {
$scope.group1 = ['grp1', 'grp2'];
$scope.group2 = [['abc', 'def'],['adf','cdf']];
$scope.value = [[['value1','value2']],[['value3','value4']]];
}
Try hardcoded way:
<div ng-controller = "fessCntrl">
<ul ng-repeat="group in group1">
<li>{{group}}</li>
<li>{{group2[$index][0]}} {{group2[$index][1]}}</li>
<li>{{value[$index][0][0]}} {{value[$index][0][1]}}</li>
</ul>
</div>
Demo Fiddle
But if you want to invoke controller, I would write:
<div ng-controller = "fessCntrl">
<ul ng-repeat="group in group1">
<li>{{group}}</li>
<li>{{printGroup(group2[$index])}}</li>
<li>{{printGroup(value[$index])}}</li>
</ul>
</div>
and method:
$scope.printGroup = function (group) {
var buff = '';
angular.forEach(group, function(val){
buff = buff + ' ' + val
});
return buff;
};
Demo 2 Fiddle

Resources