I have an array with list of values like the following
[
{
"name":"x",
"type":"deposit",
"deposit_amount":100
}
{
"name":"x",
"type":"withdraw",
"withdraw_amount":10
}
{
"name":"y",
"type":"deposit",
"deposit_amount":20
}
{
"name":"y",
"type":"withdraw",
"withdraw_amount":20
}
]
I need to add "deposit_amount" of objects having type as "deposit" and "withdraw_amount" of objects having type as "withdraw".
I have tried using ng-init using ng-repeat
<th ng-show="$last" ng-init="obj.total.deposit_amount = obj.total.deposit_amount + data.deposit_amount">Amount Collected : {{obj.total.deposit_amount}}</th>
<th ng-show="$last" ng-init="obj.total.withdraw_amount = obj.total.withdraw_amount + data.withdraw_amount">Amount Withdrawn :{{obj.total.withdraw_amount}}</th>
When I use this I got the expected one,but each time I click on search the total values get updating.
Any help would be Appreciated.Thanks
Handle that with javascript like this or something.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.data = [{"name":"x","type":"deposit","deposit_amount":100},
{"name":"x", "type":"withdraw", "withdraw_amount":10},
{"name":"y", "type":"deposit", "deposit_amount":20},
{"name":"y", "type":"withdraw", "withdraw_amount":20}
];
$scope.totalDeposit = 0;
$scope.totalWithdraw = 0;
angular.forEach($scope.data, function(obj) {
if(obj.type == 'deposit') {
$scope.totalDeposit += obj.deposit_amount;
}
else if(obj.type == 'withdraw') {
$scope.totalWithdraw += obj.withdraw_amount;
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div>Amount Collected : {{totalDeposit}}</div>
<div>Amount Withdrawn : {{totalWithdraw}}</div>
</div>
var x={}; x.test='xyz'; console.log(x);
--> obj.total.deposit_amount = 'x'
Related
I am fairly new to AngularJS and I have been reading some answers here but nothing worked out. I have a json file from a controller that I display in a select. I want to set the selected value based on the text value.This is what I have so far.
HTML:
<div ng-app="userModule" ng-controller="userCtrl">
<div class="row">
<div class="col-md-6">
<label>User Name:</label> <br />
<select ng-model="users.selectedUser" class="form-control" ng-options="item.UserName as item.UserName for item in users.availableOptions"></select>
</div>
Controller:
<script>
var _$http;
var _$scope;
var oldUser = #Html.Raw(Json.Serialize(ViewData["UserName"]));
var oldRole = #Html.Raw(Json.Serialize(ViewData["RoleName"]));
angular.module('userModule', [])
.controller('userCtrl', xConstructor);
function xConstructor($scope, $http) {
_$http = $http;
_$scope = $scope;
$http.get("/RoleManagement/GetUserData").then(xReceive);
$http.get("/RoleManagement/GetRoleData").then(roleReceive);
_$scope.submit = function () {
//alert("Here:" + _$scope.selectedUser);
$http.get("/RoleManagement/PutUserRoleData?UserId=" + _$scope.selectedUser.UserId + "&RoleId=" + _$scope.selectedRole.RoleId).then(writeSuccess);
}
}
function xReceive(userObject) {
_$scope.users = {
availableOptions: userObject.data,
**selectedUser: { UserId: oldId, UserName: oldUser } //What to put here?**
};
alert(JSON.stringify(JSON.stringify(_$scope.users.selectedUser));
}
</script>
Or any other suggestions on how to do this?
The problem is you are not mapping the model to any element in the array you have.
Assuming you have the id of the user you want to select this is what you do:
function xReceive(userObject) {
_$scope.users = {
availableOptions: userObject.data,
selectedUser: null
};
let selectedUser;
for (let i = 0; i < userObject.data.length; i++) {
if (userObject.data[i].id === oldId) {
selectedUser = userObject.data[i];
break;
}
}
if (selectedUser) {
_$scope.users.selectedUser = selectedUser;
}
alert(JSON.stringify(JSON.stringify(_$scope.users.selectedUser));
}
Also note, you can do this to just select the first one:
_$scope.users.selectedUser = _$scope.users.availableOptions[0];
I am using Asp.MVC 5 for an application and I want to generate many checkboxes with different angularjs models, and I thought the best option is by using array model in angularjs. I tried the code below inside a foreach:
#{
int i = 0;
foreach (var selectedVesselViewModel in Model.SelectedVesselViewModels)
{
using (Html.BeginForm("SelectNotificaiton", "Admin", new { area = "DashBoard" }, FormMethod.Post, new { id = "filterVesselsForm_" + i}))
{
#Html.HiddenFor(item => selectedVesselViewModel.VesselId, new {ng_model= "SelectedVessels[" + i + "].VesselId" })
<li class="row">
<div class="col-md-10">
<a href="#" class="text-admin-area">
#selectedVesselViewModel.VesselName
</a>
</div>
<div class="col-md-2">
<div class="pull-right">
<div class="checkbox checkbox-inline">
#Html.CheckBoxFor(item => selectedVesselViewModel.Selected,
new {id = "SelectedVesselViewModels_"+i+"__Selected",
onchange ="document.getElementById('filterVesselsForm_"+i+"').submit()",
ng_model = "SelectedVessels[" + i + "].Selected"
})
<label for="SelectedVesselViewModels_#(i++)__Selected"></label>
</div>
</div>
</div>
</li>
}
}
}
i variable is an incrementing variable:
in the angularjs controller I have something like this:
(function (app) {
"use strict";
app.controller("DashboardCtrl", ['$scope',
function ($scope) {
function init() {
// $scope.SelectedVessels = [];
}
$scope.SelectedVessels = [];
init();
$scope.RefreshSideBarVessels = function() {
angular.forEach($scope.SelectedVessels, function (value, key) {
alert($scope.SelectedVessels[key].VesselId);
});
}
}]);
})(adminModule);
When I use angularjs foreach loop the $scope.SelectedVessels seems to be empty but I dont know why!
angular.forEach($scope.SelectedVessels, function (value, key) {
alert($scope.SelectedVessels[key].Selected);
});
Does anybody know where is the problem, why I cant access the inner properties of the $scope.SelectedVessels array and why it is empty ?
How you are adding values to your array ie. $scope.SelectedVessels is important
Please have a look at below example.
var values = {name: 'Raja', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key) {
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: Raja', 'gender: male']);
Here is the solution to this problem:
I had to use ng-init to each checkbox to instantiate the ng-model.
#Html.CheckBoxFor(item => selectedVesselViewModel.Selected,
new {id = "SelectedVesselViewModels_"+i+"__Selected",
onchange ="document.getElementById('filterVesselsForm_"+i+"').submit()",
ng_model = "SelectedVessels[" + i + "].Selected",
ng_init = "SelectedVessels[" + i + "].Selected="+ selectedVesselViewModel.Selected.ToString().ToLower()
})
First off , its ng-model not ng_model (- vs _) but that could be typo.
Second, try this code
$scope.onChange = function (index, value) {
$scope.SelectedVessels[index] = value;
}
#Html.CheckBoxFor(item => selectedVesselViewModel.Selected,
SelectedVessels[i] = selectedVesselViewModel.Selected
new {id = "SelectedVesselViewModels_"+i+"__Selected",
onchange ="document.getElementById('filterVesselsForm_"+i+"').submit()",
ng-model = "SelectedVessels[" + i + "].Selected",
on-change="onChange(i,selectedVesselViewModel.Selected)
})
I've seen a few posts asking the same question but I can't make it work. I'm quite new to angular so I would need help.
I'm trying to insert a new income with tags.
I get thoses tags from a service and display them like this :
<label ng-repeat="tag in tags">
<input type="checkbox" ng-model="tags_chosen" name="tags_chosen[tag]" ng-true-value="<%tag.id%>"/> <%tag.name%>
</label>
When I try to get back the checkbox values in angular, it doesn't work :
this.addIncome = function($scope) {
var data = {
'project_id':$scope.project_id,
'amount':$scope.amount,
'payment_date':$scope.payment_date,
'tags':$scope.tag_chosen,
'description':$scope.description,
'type':$scope.type
};
return $http.post(URL.BASE_API + 'income/store',data).
success(function(response) {
ServicesStatus.return = response;
}).error(function(response) {
console.log('Service error');
});
};
How could I do that ?
Thanks !
try this:
$scope.tag_chosen =[];
$scope.toggleSelection = function ( deviceId, $event ) {
var checkbox = $event.target;
var action=(checkbox.checked ? 'add':'remove');
var idx = $scope.tag_chosen.indexOf( deviceId );
// is currently selected
if (action=='remove' && idx != -1 ) {
$scope.tag_chosen .splice( idx, 1 );
}
// is newly selected
if (action=='add' && idx == -1 ) {
$scope.tag_chosen.push( deviceId );
}
and in html >>
ng-click="toggleSelection(yourcjeckbox value,$event)"
The same way, I can manually do filter: { category : 'Popular'} in ng-repeat, I'd like to be able to do the same thing with the dropdown.
I was able to make the basics work. I have two problems: I don't want the categories to duplicate themselves in the dropdown, I'd like to be able to see everything categorized "Popular" when I select "Popular" in the dropdown.
Here is my HTML:
<div ng-controller="SuperCtrl" class="row">
<ul class="small-12 medium-12 columns">
<select ng-model="find" ng-options="entry.category for entry in parsedEntries"><option value="">Select Category</option></select>.
<li ng-repeat="entry in parsedEntries | filter: find">
<strong>{{ entry.title }} </strong><br>
{{ entry.description }}
</li>
</ul></div>
Here is the controller:
app.controller('SuperCtrl', ['$scope', '$http', function($scope,$http) {
var url = 'https://spreadsheets.google.com/feeds/list/1lZWwacSVxTD_ciOsuNsrzeMTNAl0Dj8SOrbaMqPKM7U/od6/public/values?alt=json'
var parse = function(entry) {
var category = entry['gsx$category']['$t'];
var description = entry['gsx$description']['$t'];
var title = entry['gsx$title']['$t'];
return {
category: category,
description: description,
title: title
};
}
$http.get(url)
.success(function(response) {
var entries = response['feed']['entry'];
$scope.parsedEntries = [];
for (key in entries) {
var content = entries[key];
$scope.parsedEntries.push(parse(content));
}
});
}]);
Got it working as you want with :
<select ng-model="find" ng-options="entry.category as entry.category for entry in parsedEntries | unique: 'category'">
The unique filter is from angular-filter. It requires to add 'angular.filter' you to your modules dependencies:
var app = angular.module('myApp', ['angular.filter']);
See fiddle
NB: Not a problem by itself but I took the <select> element out of the <ul> one.
Just put unique categories into in a string array called categories, sort the array, and display it with ng-options:
<select ng-model="find" ng-options="category as category for category in categories"><option value="">Select Category</option></select>.
Append this to your code after your parse function, and delete the $http.get you had. This defines a contains function and builds the array at the same time the objects come back:
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
};
$http.get(url)
.success(function(response) {
var entries = response['feed']['entry'];
$scope.parsedEntries = [];
$scope.categories = [];
for (key in entries) {
var content = entries[key];
var obj = parse(content);
$scope.parsedEntries.push(obj);
if (!contains($scope.categories, obj.category))
{
$scope.categories.push(obj.category);
}
}
$scope.categories.sort();
})
I have created an angularjs application for printing the Indian people count as well as those who have vote eligible count values,
The application is working fine but i dont know how to get indians and vote eligible counts while iterating
Working Demo
<div ng-app='myApp' ng-controller="Controller">
<div ng-init="indiansCount = 0" ng-repeat="emp in records">
<b>Can Vote :</b><br>
<b>Indians :</b> {{getIndiansCount(emp.country, indiansCount)}}
<div ng-repeat="empl in emp">
{{empl.country}}<br>
{{empl.employee.name}}<br>
{{empl.employee.canVote}}
<hr>
</div>
</div>
</div>
Can anyone please tell me some suggestion for this
Your emp.country is undefined, because emp is a collection of employees. You could do this instead:
HTML:
<b>Indians :</b> {{getIndiansCount(emp, indiansCount)}}
JS:
$scope.getIndiansCount = function(employees, count) {
angular.forEach(employees, function(employee) {
if(employee && employee.country === "Indian") {
count++;
}
});
return count;
};
DEMO
EDIT
In case you don't want to add loops, you can indeed use the ng-repeat to execute an increment function.
First you need to initialize an array for indianCounts (and voteCounts) in your scope:
app.controller('Controller', function ($scope) {
$scope.indiansCount = []; // Like this
$scope.voteCount = [];
...
Then you need these functions:
$scope.initCount = function(i) {
$scope.indiansCount[i] = 0;
$scope.voteCount[i] = 0;
}
$scope.incrementCount = function(empl, i) {
if(empl.country === "Indian") {
$scope.indiansCount[i]++;
}
if(empl.employee && empl.employee.canVote === true) {
$scope.voteCount[i]++;
}
};
Finally, here is the HTML with all the stuff needed:
<div ng-app='myApp' ng-controller="Controller">
<!-- Here you keep a trace of the current $index with i -->
<div ng-init="initCount(i = $index)" ng-repeat="emp in records">
<b>Can Vote :</b> {{voteCount[i]}}<br>
<b>Indians :</b> {{indiansCount[i]}}
<div ng-repeat="empl in emp" ng-init="incrementCount(empl, i)">
{{empl.country}}<br>
{{empl.employee.name}}<br>
{{empl.employee.canVote}}
<hr>
</div>
</div>
</div>
Here is the JSFiddle updated
I have updated you jsFiddle.
Added 3 filters -
1. Indian
2. CanVote
3. IndianCanVote
you can see it working here - http://jsfiddle.net/tmu9kukz/7/
Filters
app.filter("Indian", function() {
return function(records) {
var totalIndianCount = 0;
angular.forEach(records, function(emp, empKey) {
angular.forEach(emp, function(oneEmp, oneEmpKey) {
if (oneEmp.country === "Indian") {
totalIndianCount += 1;
}
});
});
return totalIndianCount;
}
});
app.filter("CanVote", function() {
return function(records) {
var totalCanVote = 0;
angular.forEach(records, function(emp, empKey) {
angular.forEach(emp, function(oneEmp, oneEmpKey) {
if (oneEmp.employee.canVote) {
totalCanVote += 1;
}
});
});
return totalCanVote;
}
});
app.filter("IndianCanVote", function() {
return function(records) {
var totalCanVote = 0;
angular.forEach(records, function(emp, empKey) {
angular.forEach(emp, function(oneEmp, oneEmpKey) {
if (oneEmp.country === "Indian" && oneEmp.employee.canVote) {
totalCanVote += 1;
}
});
});
return totalCanVote;
}
})
HTML
<div> Total Indians : {{records | Indian}} </div>
<div> Total Can Vote : {{records | CanVote}} </div>
<div> Total Can Vote : {{records | IndianCanVote}} </div>