angularjs checkbox append to scope variable - json

I have a table as follows:
<tr ng-repeat="user in users">
<td>{{user.fields.first_name}}, {{ user.fields.last_name }}</td>
<td>
<input type="checkbox">
</td>
</tr>
and the json is as follows:
{
"users":
[
{ "fields": {"first_name": "sam", "last_name": "smith"}, "model": "auth.user", "pk": 3},
{ "fields": {"first_name": "tom", "last_name": "moody"}, "model": "auth.user", "pk": 4}
]
}
I want to have a functionality to add the pk's of the selected checkboxes to a scope variable. Since i don't have a boolean field for the selected in my json, how will i approach this?

You can try the code in my fiddle, the selected PKs are stored in an array call 'selected'. The pk must be unique for each user.
var app = angular.module('app', []);
var ctrl = app.controller('MyCtrl', function($scope) {
$scope.users = [{
"fields": {
"first_name": "wasif",
"last_name": "abbas"
},
"model": "auth.user",
"pk": 3
}, {
"fields": {
"first_name": "asad",
"last_name": "zaman"
},
"model": "auth.user",
"pk": 4
}, {
"fields": {
"first_name": "hes",
"last_name": "man"
},
"model": "auth.user",
"pk": 5
}];
$scope.selected = [];
$scope.toggleSelection = function toggleSelection(pk) {
var idx = $scope.selected.indexOf(pk);
// is currently selected
if (idx > -1) {
$scope.selected.splice(idx, 1);
}
// is newly selected
else {
$scope.selected.push(pk);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller='MyCtrl'>
<table>
<tr ng-repeat="user in users">
<td>{{user.fields.first_name}}, {{ user.fields.last_name }}</td>
<td>
<input type="checkbox" ng-checked="selected.indexOf(user.pk) > -1" ng-click="toggleSelection(user.pk)" />
</td>
</tr>
</table>
Selected: {{selected}}
</div>
</div>

Or you can try with ng-change, which is a bit more elegant imo:
var app = angular.module('app', []);
app.controller('AController', function($scope) {
$scope.users = [
{ "fields": {"first_name": "wasif", "last_name": "abbas"}, "model": "auth.user", "pk": 3},
{ "fields": {"first_name": "asad", "last_name": "zaman"}, "model": "auth.user", "pk": 4}
];
$scope.selectedUsers = {};
$scope.addUser = function(pk, userselected) {
if(userselected) {
$scope.selectedUsers[pk] = true;
} else {
delete $scope.selectedUsers[pk];
}
}
$scope.getSelectedUsersArray = function() {
return Object.keys($scope.selectedUsers);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="AController">
<table>
<tr ng-repeat="user in users">
<td>{{user.fields.first_name}}, {{ user.fields.last_name }}</td>
<td>
<input type="checkbox" ng-model="userselected" ng-change="addUser(user.pk, userselected)"/>
</td>
</tr>
</table>
<div>Selected: {{getSelectedUsersArray()}}</div>
</div>
</div>

Related

Retrieve Data from JSON Data Structure in Vue.js

I want retrieve Data from meal table (json data schema) to a table form in the browser. The retrievement works but unfortunately I do not know how to retrieve the data of the weekdays from my meal table and show them in the table.
How can I retrieve Monday, Tuesday, Wednesday, Thursday and Friday???
JSON DATA SCHEMA:
// 20200901152958
// http://localhost:8080/mealtable/weekly/1
{
"id": 1,
"calendarWeek": 1,
"mealTableWeek": {
"Monday": {
"id": 4,
"name": "Burger",
"type": "fleischhaltig",
"price": 2.60
},
"Tuesday": {
"id": 3,
"name": "Reishänchenpfanne",
"type": "fleischhaltig",
"price": 2.60
},
"Wednesday": {
"id": 1,
"name": "Vollkornnudeln",
"type": "vegan",
"price": 2.30
},
"Thursday": {
"id": 5,
"name": "Kartoffelpüree",
"type": "vegetarisch",
"price": 2.30
},
"Friday": {
"id": 2,
"name": "Falafel",
"type": "vegan",
"price": 1.90
}
}
}
MealTablWeekComponent.vue:
<template>
<div class="container">
<h3>Meal Table</h3>
<div class="container">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th>Meal</th>
<th>Type</th>
<th>Price in $</th>
</tr>
</thead>
<tbody>
<tr v-for="d in mealTables.mealTableWeek" v-bind:key="d.id">
<th></th>
<td>{{d.name}}</td>
<td>{{d.type}}</td>
<td>{{d.price}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
import MealTableDataService from "#/service/MealTableDataService";
export default {
name: "MealTableWeekComponent",
data() {
return {
mealTables: {
id: " ",
mealTableWeek: {
name: {
id: " ",
name: " ",
type: " ",
price: " "
}
}
}
};
},
methods: {
refreshMealTable() {
const id = this.$route.params.id;
MealTableDataService.retrieveMealTableById(id)
.then(response => {
console.log(response)
this.mealTables = response.data;
});
}
},
created() {
this.refreshMealTable();
}
};
</script>
<style scoped lang="scss">
</style>
View in the Browser:
<tr v-for="(d, key) in mealTables.mealTableWeek" v-bind:key="d.id">
<td>{{key}}</td>
<td>{{d.name}}</td>
<td>{{d.type}}</td>
<td>{{d.price}}</td>
</tr>

How to insert dropdown into dynamic table in angular7

Tried to insert dropdown inside dynamic table but i do not know how to do it.I want to insert dropdown with some values on last column.Please help anyone to find the solution.
head = [ "Name", "Age", "Gender","Action"];
details = [
{ "name": "star1", "age": "25", "gender": "male","action": "" },
{ "name": "star2", "age": "22", "gender": "female","action": "" },
{ "name": "star3", "age": "21", "gender": "male","action": "" },
{ "name": "star4", "age": "35", "gender": "female","action": "" },
];
constructor(){
this.tableHead = this.head;
this.userDetails = this.details;
}
Demo:https://stackblitz.com/edit/angular-bfs3gp?file=src/app/app.component.ts
I have made a solution for you. Can you please replace your details array to
details = [
{ name: "star1", age: "25", gender: "male", action: ["Edit", "Delete"] },
{ name: "star2", age: "22", gender: "female", action: ["Edit", "Delete"] },
{ name: "star3", age: "21", gender: "male", action: ["Edit", "Delete"] },
{ name: "star4", age: "35", gender: "female", action: ["Edit", "Delete"] }
];
Then Replace the dynamic-table.component.html to below code
<table>
<thead>
<tr class="table-head">
<th *ngFor="let tableHead of tableHeads">{{tableHead}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let tableData of tableDatas">
<td *ngFor="let colName of tableColNameGenerated"> {{colName != 'action' ? tableData[colName] : ''}}
<span *ngIf="colName == 'action'">
<select>
<option *ngFor="let opt of tableData.action">{{opt}}</option>
</select>
</span>
</td>
</tr>
</tbody>
</table>
Now I hope your concern is resolved.
Hope this helps!
Thank you.

AngularJS and HTML Table

I have json that looks like this :
[
{
"date": "25/06/2015",
"details": [
{
"p": "AM",
"b": "2500"
},
{
"p": "JL",
"b": "300"
}
]
},
{
"date": "24/06/2015",
"details": [
{
"p": "AM",
"b": "2300"
},
{
"p": "JL",
"b": "1300"
}
]
}
]
I want to write the data to an html table using angularjs, but I want the value of date.details.p to determine which column the value of date.details.b should go in. So, for example the value date.details.b will always go in column 2 if date.details.p = 'AM'.
The JSON data will not always contain data that would relate to each column, nor can the order of the details array be guaranteed.
Any ideas gratefully received.
EDIT
The expected output would be
Date AM JL
25/06/2015 2500 300
24/06/2015 2300 1300
Based on the limited info I can suggest you can use ngShow.
<tr>
<td class="ColumnTwo">
<span data-ng-show="checkAM(date)">{{date.details.p}}</span>
</td>
</tr>
In the function checkAM you can check if date.details.p == "AM"
Based on the situation you can use
ngSwitch
ngIf
Also check out https://stackoverflow.com/a/15810462/2489860
Try this:
<table>
<tr>
<th>Date</th>
<th>AM</th>
<th>JL</th>
</tr>
<tr ng-repeat="item in data">
<td>{{ item.date }}</td>
<td ng-repeat="detail in item.details">
<span ng-show="detail.p=='AM' && $index == 0">{{ detail.b }}</span>
<span ng-show="detail.p=='JL' && $index == 1">{{ detail.b }}</span>
</td>
</tr>
</table>
You can see and run the complete code below:
angular.module('app', [])
.controller('ctrl', function ($scope) {
$scope.data = [
{
"date": "25/06/2015",
"details": [
{
"p": "AM",
"b": "2500"
},
{
"p": "JL",
"b": "300"
}
]
},
{
"date": "24/06/2015",
"details": [
{
"p": "AM",
"b": "2300"
},
{
"p": "JL",
"b": "1300"
}
]
}
];
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-app="app">
<div ng-controller="ctrl">
<table>
<tr>
<th>Date</th>
<th>AM</th>
<th>JL</th>
</tr>
<tr ng-repeat="item in data">
<td>{{ item.date }}</td>
<td ng-repeat="detail in item.details">
<span ng-show="detail.p=='AM' && $index == 0">{{ detail.b }}</span>
<span ng-show="detail.p=='JL' && $index == 1">{{ detail.b }}</span>
</td>
</tr>
</table>
</div>
</body>
</html>

I can't load json object I created

I am using KnockoutJS for a web page. I created a JSON object to mimic values from server. Each time I run the page I get an empty record. Am I missing something?
var data ={ "employee": [{
"SiteId": 9,
"SystemId": 1,
"SystemName": "Glocus",
"ManualLink": "http://www.Glocus.com/Guide",
"ContactNo": "301-489-8989",
"UserAccount": [{
"AccountId": 1,
"AccountName": "Sisij",
"AccountType": "Customer System",
"Username": "Tybeke"
"Password": "*****",
}, {
"AccountId": 2,
"AccountName": "gabid",
"AccountType": "System System",
"Username": "Tybeke"
"Password": "*****",
}]
}, {
"SiteId": "1",
"SystemId": 1,
"SystemName": "TheSecondWorld",
"ManualLink": "http://www.TheSecondWorld.com/Guideplan",
"ContactNo": "301-489-8989",
"UserAccount": [{
"AccountId": 1,
"AccountName": "Uniqex",
"AccountType": "Customer System",
"Username": "TUniqux"
"Password": "*****",
}, {
"AccountId": 2,
"AccountName": "Celind",
"AccountType": "System System",
"Username": "GCElinds"
"Password": "*****",
}]
}]};
var ViewModel = function () {
var self = this;
var hello = ko.mapping.fromJS(data);
self.items = ko.observableArray(hello);
};
ko.applyBindings(new ViewModel());
Here is my knockoutJS Html code:
<div>
<span>Account</span>
<hr/>
<table>
<thead>
<tr>
<th>System Name</th>
<th>Manual link</th>
<th>Contact No</th>
</tr>
</thead>
<tbody data-bind="foreach: items.employee">
<tr>
<td data-bind="text :SystemName"></td>
<td data-bind="text : ManualLink"></td>
<td data-bind="text : ContactNo "></td>
</tr>
</tbody>
</table>
<hr/>
</div>
I have wasted so much time trying to get it right. Any help will be appreciated.
ko.mapping is used to create viewmodels. So you wouldn't actually nest view models in this case; you would just use the JSON to create one:
viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
http://jsfiddle.net/32765/1/

How to use this json in handlebars js

Here is the full code.
HTML part:
<script id="company_template" type="text/x-handlebars-template">
{{#each CDataMap}}
<div>{{this}}</div>
{{/each}}
<p></p>
</script>
JS part
var source = $("#company_template").html();
var template = Handlebars.compile(source);
var data= {
"CDataMap" : {
"name": "Jim Cowart",
"location": {
"city": {
"name": "Chattanooga",
"population": 167674
},
"state": {
"name": "Tennessee",
"abbreviation": "TN",
"population": 6403000
}
},
"company": "appendTo"
}
};
$("p").append(template(data));
I want to use this using handlebars js.
When am using it am getting object object display only.
I need the correct code.
The problem with your example is that CDataMap is not an array of objects, so you cannot iterate through them.
This is a valid example:
<script>
(function ($) {
$(function () {
var source = $("#company_template").html();
var template = Handlebars.compile(source);
var data = {
"CDataMap": [{
"name": "Jim Cowart",
"location": {
"city": {
"name": "Chattanooga",
"population": 167674
},
"state": {
"name": "Tennessee",
"abbreviation": "TN",
"population": 6403000
}
},
"company": "appendTo"
}]
};
$("p").append(template(data));
});
})(jQuery);
</script>
And also the p tag or any element you'll use to put the result in must be outside of the template, like this:
<script id="company_template" type="text/x-handlebars-template">
{{#each CDataMap}}
<div>{{this.name}}</div>
<div>{{this.location.city.name}}</div>
{{/each}}
</script>
<p></p>
Handlebar each expects iterative elements. Data which you are supplying needs to be modified.
Below code works
<script id="company_template" type="text/x-handlebarstemplate">
{{#each CDataMap}}
<div>Name : {{this.name}} <br/>
Location: {{this.location.city.name}} <br />
Population: {{this.location.city.population}}
</div>
{{/each}}
</script>
<p></p>
JS side
var data= {
"CDataMap" : [
{
"name": "Jim Cowart",
"location": {
"city": {
"name": "New york",
"population": 494949494
}
}
},
]
};
var templateSource = $("#company_template").html();
template = Handlebars.compile(templateSource);
studentHTML = template(data);
$("p").append(studentHTML);