Angularjs Dynamic Text Fields and multiply two field - angularjs

Hi I have a Json Like this
[
{
"id": 1,
"name": "Furniture & Fixture",
"choices": [
{
"req_goods": "",
"qty": "10",
"rate": "",
"total": ""
}
]
},
{
"id": 2,
"name": "Miscellaneous Property",
"choices": [
{
"req_goods": "",
"qty": "",
"rate": "",
"total": ""
}
]
},
{
"id": 3,
"name": "Office Equipment",
"choices": [
{
"req_goods": "",
"qty": "",
"rate": "",
"total": ""
}
]
}
]
here choices are my dynamic fields user can add as much choices as they want, my add/remove js is like this
$scope.addNewChoice = function(id){
$scope.capital_budgets[id].choices.push({});
};
$scope.removeChoice = function(parent_id,id) {
$scope.capital_budgets[parent_id].choices.splice(id,1);
};
my html
<div ng-repeat="cb in capital_budgets">
<div><b><% $index+1 %> <% cb.name %></b></div>
<div ng-repeat="choice in cb.choices">
<input type="text" ng-model="choice.req_goods">
<input type="text" ng-model="choice.qty">
<input type="text" ng-model="choice.rate">
<input type="text" ng-model="choice.total">
<button type="button" ng-hide="$first" ng-click="removeChoice($parent.$index,$index)">-</button>
</div>
<button type="button" ng-click="addNewChoice($index)">+</button>
</div>
Now I want to calculate the total(qty*rate) of each added choices whenever they put qty and rate and put it in total field please help

One way to accomplish this would be to create a method in your controller to do the calculation and then just call it on a change of qty or rate.
controller:
$scope.updateTotal = function(choice) {
if(!choice.qty || !choice.rate) {
choice.total = 0;
} else {
choice.total = choice.qty * choice.rate;
}
};
html:
<input type="text" ng-model="choice.qty" ng-change="updateTotal(choice)">
<input type="text" ng-model="choice.rate" ng-change="updateTotal(choice)">

Related

Show JSON data as selected in Select AngularJS

I don' have a lot of knowledge about AngularJS. I have a JSON with all the data and first I created a select and according to the selected option I show some data or others according to the value, which are the IDs in the json
JSON
$scope.players = [
{
"player": {
"info": {
"position": "D",
"shirtNum": 4,
"positionInfo": "Centre/Right Central Defender"
},
"nationalTeam": {
"isoCode": "BE",
"country": "Belgium",
"demonym": "Belgian"
},
"age": "27 years 139 days",
"name": {
"first": "Toby",
"last": "Alderweireld"
},
"id": 4916,
"currentTeam": {
"name": "Tottenham Hotspur",
"teamType": "FIRST",
"shortName": "Spurs",
"id": 21
}
},
"stats": [
{
"name": "goals",
"value": 5
},
{
"name": "losses",
"value": 20
},
{
"name": "wins",
"value": 48
},
{
"name": "draws",
"value": 23
},
{
"name": "fwd_pass",
"value": 1533
},
{
"name": "goal_assist",
"value": 2
},
{
"name": "appearances",
"value": 80
},
{
"name": "mins_played",
"value": 6953
},
{
"name": "backward_pass",
"value": 308
}
]
},
...];
HTML
<select id="select-players" ng-model="Jugador" ng-options="jugador as (jugador.player.name.first + ' ' + jugador.player.name.last) for jugador in players track by jugador.player.id " ng-change="show()">
<option value="">Select a player...</option>
</select>
And I want to show the details of the player
<div class="content-player">
<div class="img-team"><span class="img-escudo"><img src="img/tottenham.png" /></span></div>
<p class="name-player">{{jugador.player.name.first}} {{jugador.player.name.last}} <span class="pos-player">{{jugador.info.positionInfo}}</span></p>
<div class="cont-desc-player">
<div class="desc-player">
<span class="txt-estadistics">{{jugador.stats.name}}</span>
<span class="num-estadistics">{{jugador.stats.value}}</span>
</div>
<div class="desc-player separador">
<span class="txt-estadistics">{{jugador.info.positionInfo}}</span>
<span class="num-estadistics">{{jugador.stats.value}}</span>
</div>
<div class="desc-player separador">
<span class="txt-estadistics">{{jugador.info.positionInfo}}</span>
<span class="num-estadistics">{{jugador.stats.value}}</span>
</div>
<div class="desc-player separador">
<span class="txt-estadistics">{{jugador.info.positionInfo}}</span>
<span class="num-estadistics">{{jugador.stats.value}}</span>
</div>
<div class="desc-player separador">
<span class="txt-estadistics">{{jugador.info.positionInfo}}</span>
<span class="num-estadistics">{{jugador.stats.value}}</span>
</div>
</div>
</div>
I don't know if I need to create in the controller one switch or using only if and else if is good and how can call it in HTML to show the details.
Thanks
You are using the iterated current object jugador in place of using the Model name Jugador. Try using Jugador.player.name.first instead of jugador.player.name.first and it should work fine if rest of the things are ok.
I also don't see the need of ng-change="show()" in your case. Model changes automatically as you change the select value and you can use it.
You use the iterated object name jugador while doing ng-repeat.

How to extract data from json using angularjs?

Here in {{msg}} I can display all jason data with Selected:true or false..
but What I need is I don't want to display all the datas, when I click Save button I want to display questions.id,option.id and selected:true or false below the textbox
we will get all the json data from $scope.questions.
Home.html
<div ng-repeat="question in filteredQuestions">
<div class="label label-warning">Question {{currentPage}} of {{totalItems}}.</div>
<div class="row">
<div class="row">
<h3>{{currentPage}}. <span ng-bind-html="question.Name"></span></h3>
</div>
</div>
<div class="row text-left options">
<div class="col-md-6" ng-repeat="option in question.Options" style="float:right;">
<div class="option">
<label class="" for="{{option.Id}}">
<h4> <input id="{{option.Id}}" type="checkbox" ng-model="option.Selected" ng-change="onSelect(question, option);" />
{{option.Name}}</h4>
</label>
</div>
</div>
</div>
<div class="center"><button ng-click="save()">Save</button></div>
<div class="center"><textarea rows="5" cols="50">{{msg}}</textarea></div>
</div>
controllers.js
var HomeController = function ($scope, $http, helper) {
/*$scope.names = response.data;
$scope.detectChange=function(){
$scope.msg = 'Data sent: '+ JSON.stringify($scope.filteredQuestions);
}*/
$scope.save = function() {
$scope.msg = 'Data sent: '+ JSON.stringify($scope.questions);
}
$scope.quizName = 'data/csharp.js';
$scope.loadQuiz = function (file) {
$http.get(file)
.then(function (res) {
$scope.quiz = res.data.quiz;
$scope.config = helper.extend({}, $scope.defaultConfig, res.data.config);
$scope.questions = $scope.config.shuffleQuestions ? helper.shuffle(res.data.questions) : res.data.questions;
$scope.totalItems = $scope.questions.length;
$scope.itemsPerPage = $scope.config.pageSize;
$scope.currentPage = 1;
$scope.mode = 'quiz';
$scope.$watch('currentPage + itemsPerPage', function () {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage),
end = begin + $scope.itemsPerPage;
$scope.filteredQuestions = $scope.questions.slice(begin, end);
});
});
}
$scope.loadQuiz($scope.quizName);
}
HomeController.$inject = ['$scope', '$http', 'helperService'];
csharp.js
{
"quiz": {
"Id": 2,
"name": "C# and .Net Framework",
"description": "C# and .Net Quiz (contains C#, .Net Framework, Linq, etc.)",
"paragraph": "In 2015 Microsoft released ASP.NET 5.ASP.NET 5 is a significant redesign of ASP.NET.ASP.NET, MVC, and Web Pages are now merged into a single framework named MVC 6.It includes the following features:Linux support OSX support Node.js supportA ngularJS supportTag ,HelpersView, ComponentsWeb ,APIGruntJS ,supportBower, supportNo ,Visual BasicNo Web Forms"
},
"config": {
"shuffleQuestions": true,
"showPager": false,
"allowBack": true,
"autoMove": false
},
"questions": [{
"Id": 1010,
"Name": "Which of the following assemblies can be stored in Global Assembly Cache?",
"QuestionTypeId": 1,
"Options": [{
"Id": 1055,
"QuestionId": 1010,
"Name": "Private Assemblies"
}, {
"Id": 1056,
"QuestionId": 1010,
"Name": "Friend Assemblies"
}, {
"Id": 1057,
"QuestionId": 1010,
"Name": "Public Assemblies"
}, {
"Id": 1058,
"QuestionId": 1010,
"Name": "Shared Assemblies"
}]
}, {
"Id": 1019,
"Name": "Which of the following does NOT represent Integer?",
"QuestionTypeId": 1,
"Options": [{
"Id": 1055,
"QuestionId": 1010,
"Name": "Char"
}, {
"Id": 1056,
"QuestionId": 1010,
"Name": "Byte"
}, {
"Id": 1057,
"QuestionId": 1010,
"Name": "Short"
}, {
"Id": 1058,
"QuestionId": 1010,
"Name": "Long"
}]
}]
}
This is my answer of above code..here Displaying all the data
Data sent: [{"Id":1013,"Name":"Which of the following is NOT an Arithmetic operator in C#.NET?","QuestionTypeId":1,"Options":[{"Id":1055,"QuestionId":1010,"Name":"** (Double Star)","$$hashKey":"00X","Selected":false},{"Id":1057,"QuestionId":1010,"Name":"+ (Plus)","$$hashKey":"00Y","Selected":false},
"$$hashKey":"00C"}]
but I want to display the all the question id's and corresponding option id's and if it is selected,selected:true otherwise false in the format of above output
If you want to change what is presented to the user after saving you should change this function:
$scope.save = function() {
$scope.msg = 'Data sent: '+ JSON.stringify($scope.questions);
}
to something like:
$scope.save = function() {
$scope.msg = 'Question IDs:';
$scope.questions.forEach(function(el){
$scope.msg += el.Id + ',';
}
}
This for example will join all the ids of the array that conains all the questions.
To add options and selections you have to ng-model the value to some variable that you will use inside your controller.
I think you should check a little guide to angularjs two-way data binding

want to display names separated by comma

here is the program for display book details.everything is working perfect but i dont know how to display authorname separated by comma(,).I want to display author name separated by comma(,) in home page.the third line is error.that I want to fix and display authornames.
home.html
<script type="text/ng-template" id="display">
<td>{{book.title}}</td>
errorline: <td>{{book.authorname}}</td>(Here i want to display author names separated by comma(,))
<td>{{book.price}}</td>
<td>
<i class="material-icons"><button type="button" data-ng-click="editBook(book)">create</button></i>
</td>
<td><i class="material-icons"><button type="button" data-ng-click="deleteBook(book)">delete_forever</button></i></td>
</script>
controllers.js
$scope.online_bookauthors= 'data/bookauthors.js';
$scope.loadbookauthorscadentials= function (file) {
$http.get(file)
.then(function (result) {
$scope.bookauthorsresult=result;
$scope.bookauthorslist=$scope.bookauthorsresult.data.bookauthorsdetails;
})
}
$scope.loadbookauthorscadentials($scope.online_bookauthors);
bookauthors.js
{
"bookauthors": {
"Id": 1,
"name": "Book Author Details"
},
"bookauthorsdetails": [{
"bookid": 1,
"title": "War and piece",
"price": 100,
"authors": [{
"authorid": 1,
"authorname": "Tolstoy"
}, {
"authorid": 2,
"authorname": "Herman melville"
}]
}, {
"bookid": 2,
"title": "moby Dick",
"price": 200,
"authors": [{
"authorid": 1,
"authorname": "Tolstoy"
}, {
"authorid": 2,
"authorname": "Herman melville"
}, {
"authorid": 3,
"authorname": "Jane Austen"
}]
}],
"selected": {}
}
<div ng-repeat="author in book.authors">{{ ($index !== book.authors.length-1) ? author.authorname+',' : author.authorname }}</div>

How to filter set of items from list of items - AngularJS

I have two scope variables in angularJS. One storing "all the subcategories" and other storing "categories and their respective subcategories".
$scope.Categories = [
{
"subcategories": [
{
"scname": "Sugar",
"scid": "5"
},
{
"scname": "Salt",
"scid": "6"
},
{
"scname": "Jaggery",
"scid": "7"
}
],
"name": "Salt and Sugar",
"id": "1",
"image": "/images/salt_sugar.png"
},
{
"subcategories": [
{
"scname": "Tea",
"scid": "8"
},
{
"scname": "Coffee",
"scid": "9"
},
{
"scname": "Tea Bags",
"scid": "162"
}
],
"name": "Tea and Coffee",
"id": "2",
"image": "/images/tea_and_coffee.png"
}
]
$scope.subcategories = [
{
"name": "Sugar",
"id": "5"
},
{
"name": "Salt",
"id": "6"
},
{
"name": "Jaggery",
"id": "7"
},
{
"name": "Tea",
"id": "8"
},
{
"name": "Coffee",
"id": "9"
},
{
"name": "Tea Bags",
"id": "162"
}
]
On selecting a category i want to display mapped and unmapped subcategories with that particular category. First one is very easy. How to filter second one? for example -
on selecting "Tea and Coffee" unmapped categories should be - Sugar, salt, Jaggery
on selecting "Salt and Sugar" unmapped categories should be - Tea, Coffee, Tea Bags
This is how I am listing mapped categories:
<TR align="center">
<TD>
<select ng-options="c as c.name for c in Categories|orderBy:'name' " ng-model="selectedCategory" size="10"> </select>
</TD>
<TD>
<select ng-options="sc as sc.scname for sc in selectedCategory.subcategories|orderBy:'scname' " ng-model="SelectedMappedSubCategory" size="10"> </select>
</TD>
<TD>
<select ng-options="sc as sc.name for sc in SubCategories | orderBy:'name' | ???????" ng-model="SelectedUnMappedSubCategory" size="10"> </select>
</TD>
</tr>
What logic should I use in-place if ?????????
If I understood correctly, why not just filter it?
| filter: {scname: SelectedUnMappedSubCategory.scname}
EDIT:
I can see that you edited the code you originally posted. I think you can achieve what you are trying to do, by this:
| filter: {id: SelectedUnMappedSubCategory.scid}
Create a customized filter:
sampleApp.filter('filterSubcategories', function() {
return function(input, filterkey) {
var filtered = [];
if (filterkey) {
for (var i = 0; i < input.length; ++i) {
var item = input[i];
var found = false;
for (var j = 0; j < filterkey.length; ++j) {
if (item.id == filterkey[j].scid) {
found = true;
break;
}
}
if (!found){
filtered.push(item);
}
}
}
return filtered;
};
});
and use this like:
<TD>
<select ng-options="sc as sc.name for sc in SubCategories | filterSubcategories:selectedCategory.subcategories | orderBy:'name'" ng-model="SelectedUnMappedSubCategory" size="10"> </select>
</TD>

How fill dropdown menu

I´m working with bootstrap and angularjs for the user interface and google appengine with java as a backend.
Just now I have a problem filling a dropdown menu, I see an empty list so I suspect that the problem is in the html code.
Front end:
<div class="dropdown" >
<select id="mySelPartido" class="form-control">
<option ng-repeat="partido in data.locations.partidos"
ng-selected="partido.selected" ng-model="partido.partido">{{partido.partido}}</option>
</select>
</div>
js in angular code (I debug this code and it works!):
$scope.status = 'loading...';
$scope.partido = "Select partidos";
$scope.data = {
"locations": {}
};
$http.get('https://myservice.appspot.com/_ah/api/partidoendpoint/v1/partido')
.then(function (res) {
$scope.data.locations.partidos = res.data.items;
$scope.status = "loaded "
+ $scope.data.locations.partidos.length
+ " partidos.";
});
My service response from app engine backend:
{
"items": [
{
"id": {
"kind": "Partido",
"appId": "s~myservice",
"id": "5066549580791808",
"parent": {
"kind": "Provincia",
"appId": "s~myservice",
"id": "5086253011697664",
"complete": true
},
"complete": true
},
"name": "Florencio Varela",
"kind": "partidoendpoint#resourcesItem"
},
{
"id": {
"kind": "Partido",
"appId": "s~myservice",
"id": "5094432508477440",
"parent": {
"kind": "Provincia",
"appId": "s~myservice",
"id": "5086253011697664",
"complete": true
},
"complete": true
},
"name": "La Matanza",
"kind": "partidoendpoint#resourcesItem"
}
],
"kind": "partidoendpoint#resources",
"etag": "\"PQS12KaO4-dKVfv_BcCoEkbIN9g/GvZKzZUnrHEP8TKWybTkd_fJbnc\""
}
Check the angular documentation for select.
Maybe try use the ngOptions directive in the select element. Example :
function demo($scope) {
$scope.items = [
{ name: 'foo' },
{ name: 'bar' },
{ name: 'baz' }
];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="demo">
<select ng-options="item.name for item in items"
ng-model="selected">
</select>
<p>You have selected : {{ selected }}
</div>

Resources