knockout js json bind list to clicked listitem - javascript

I would like to select a specific location by Continent / Country / State / etc.
I get a JSON and I managed to display/select the Continent, but I cannot get the list of Countries to populate.
I am rather new to knockout and JS, so I am probably doing something wrong (I managed to do this based on the live examples from knockout, but those were using select, and I cannot seem to get it to work on ul)
The JSON (composed by hand, so might have errors)
var Continent = [
{ Name: "Europe", Countries: [{ Name: "England", ID: 1 }, { Name: "Wales", ID: 2 }] },
{ Name: "America", Countries: [{ Name: "US", ID: 3 }, { Name: "Canada", ID: 4 }] },
{ Name: "Asia", Countries: [{ Name: "India", ID: 5 }, { Name: "China", ID: 6 }] }
];
The javascript:
var locationVM = function () {
var self = this;
self.selectedContinent = ko.observable("none");
self.selectedCountry = ko.observable();
self.selectedContinent.subscribe(function () {
self.selectedCountry(undefined);
});
self.onClickContinent = function (data) {
self.selectedContinent(data.Name);
};
};
ko.applyBindings(new locationVM());
The HTML
<div>
<ul data-bind="foreach: Continent">
<li data-bind="text: Name, click: $parent.onClickContinent" />
</ul>
</div>Selected Continent : <span data-bind="text: selectedContinent">text</span>
<div data-bind="with: selectedContinent">
<ul data-bind="foreach: Countries">
<li data-bind="text: Name" />
</ul>
</div>
and here is the fiddle http://jsfiddle.net/norbert/WB46V/
Also, if there is anything I missed, or is not needed, please point it out, or provide link for further studies ;)

You're trying to set the continent value to a string and then later trying to iterate thru the string. What you need to do is set the continent to the data.
Something like this:
self.selectedContinent(data);
Working fiddle here.
http://jsfiddle.net/WB46V/6/
Just to add, I haven't used knockout before, so my solution in the fiddle might not be the best one.

Related

Change select drop-down option based on input value using autocomplete in Knockout JS

Using Knockout JS, when a user types into an input field and selects a value (ex: Fruit) using jquery-ui autocomplete selection, I'm trying to change the select drop-down of options in a separate drop-down.
Example scenario:
(1) User begins to type "Fru.."
(2) Selects "Fruit" in autocomplete input field.
(3) Dropdown options changes based on the value: "Fruit"
(4) Dropdown options only shows "Apples" or other options with equals id (ex: ABC)
Autocomplete Input Field
HTML
<input type="text"
id="searchItem"
placeholder="Search"
tabindex="0"
data-bind="textInput: searchItem, valueUpdate: 'onkeyup'"/>
ViewModel/JQuery (Autocomplete)
// Search Item
$(function() {
var searchItem = [
{ id: "ABC", name: "Fruit" },
{ id: "DEF", name: "Animal" },
{ id: "GHI", name: "Color" },
{ id: "JKL", name: "Clothing" }
];
$("#searchItem").autocomplete({
source: searchItem
});
});
Select dropdown
HTML
<select class="form-control"
id="alphabetList"
data-toggle="tooltip"
tabindex="0"
data-bind=" foreach: { data: alphabetList, as: 'item' }, value: selectedItem">
<option data-bind=" attr: { 'value': item.id }, text: item.name"></option>
</select>
ViewModel
// Alphabet List
this.alphabetList = ko.observableArray([
{ id: "ABC", name: "Apples" },
{ id: "DEF", name: "Dog" },
{ id: "GHI", name: "Green" },
{ id: "JKL", name: "Jacket" }
]);
On selection of an item in autocomplete, populate an observable called selectedId. Then create a computed property which filters the alphabetList based on selectedId
You have not mentioned where this autocomplete code exists. But, since you have mentioned ViewModel, I'm assuming you have access to the viewModel's instance in your jquery code.
Also, you don't need to use the foreach binding for displaying options. You can use options binding.
Here's a working snippet with all these changes:
var viewModel = function() {
var self = this;
self.selectedAlphabet = ko.observable();
self.selectedId = ko.observable();
self.searchItem = ko.observable();
self.alphabetList = ko.observableArray([
{ id: "ABC", name: "Apples" },
{ id: "DEF", name: "Dog" },
{ id: "GHI", name: "Green" },
{ id: "JKL", name: "Jacket" }
]);
// this gets triggerred everytime selectedId changes
self.availableAlphabetList = ko.pureComputed(() => {
return self.alphabetList().filter(item => item.id == self.selectedId());
});
}
// I have created an instance to use it in jquery code
var instance = new viewModel();
ko.applyBindings(instance);
$(function() {
var searchItem = [
{ id: "ABC", name: "Fruit" },
{ id: "DEF", name: "Animal" },
{ id: "GHI", name: "Color" },
{ id: "JKL", name: "Clothing" }];
$("#searchItem").autocomplete({
// creating an array with a "label" property for autocomplete
source: searchItem.map(function(item) {
return {
label: item.name,
id: item.id
}
}),
// on select populate the selectedId
select: function(event, ui) {
// if this jquery code is within viewModel, then use "self.selectedId"
instance.selectedId(ui.item.id)
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery-ui.css">
<input type="text" id="searchItem" placeholder="Search" tabindex="0" data-bind="textInput: searchItem, valueUpdate: 'onkeyup'" />
<select class="form-control" id="alphabetList" data-toggle="tooltip" tabindex="0" data-bind="options: availableAlphabetList,
optionsText: 'name',
optionsValue: 'id',
value: selectedAlphabet
optionsCaption: 'Choose..'">
</select>
You can also go through this question which has good answers for creating a custom binding for autocomplete

How can I use ng-repeat to iterate through arrays associated using dynamic keys

I am trying to use ng-repeat to iterate through an array of objects and use each objects ID to look up the data binded to a checklist model.
I have the following javascript object in a project I'm working on:
{
diagnosis: {
mainfractures: [
{
id: "metacarpal",
textinput_id: "metacarpal_text",
title: "5th Metacarpal",
},
{
id: "proximal_phalanx",
textinput_id: "proximal_phalanx_text",
title: "Proximal Phalanx",
},
{
id: "middle_phalanx",
textinput_id: "middle_phalanx_text",
title: "Middle Phalanx",
},
{
id: "distal_phalanx",
textinput_id: "distal_phalanx_text",
title: "Distal Phalanx",
},
{
id: "scaphoid_fracture",
textinput_id: "scaphoid_fracture_text",
title: "Scaphoid Fracture",
}
]
}}
Here is what I have for my checklist model. As the user selects a checkbox, a value is binded to the array associated with that fracture.
$scope.checklists = {
"diagnosis": {
metacarpal: [],
proximal_phalanx: [],
middle_phalanx: [],
distal_phalanx: [],
scaphoid_fracture: []
}
}
Checklist Image Example
Once a users makes a selection similar to the image above the the checklist model for metacarpal should look like this: metacarpal: ["head"]
What I'm trying to do is list each of the users selection in bulletpoint via fracture.id. I'm trying to accomplish it with this piece of code but it's only listed the fracture title so far. is it a problem with trying to interpolate fracture.id into ng-repeat?
<div ng-repeat="fracture in diagnosis.mainfractures">
<div > <!--ng-if="checklists['diagnosis'][fracture.id] > 0"-->
<h4>{{ fracture.title }}</h4>
<div class="row">
<ul type="disc">
<li ng-repeat="selection in checklists['diagnosis'][fracture.id]">
• {{ capitalize(selection) }}
</li>
</ul>
</div>
</div>
</div>
Based on your supplied code, I'd have to say your issue is actually due to JS syntax errors. You're missing commas after each object item and there is a random double quote here scaphoid_fracture"[].
$scope.checklists = {
"diagnosis": {
metacarpal: []
proximal_phalanx: []
middle_phalanx: []
distal_phalanx: []
scaphoid_fracture"[]
}
}
Here is a fully working jsfiddle
Adjusted the code a bit:
capitalize ->
uppercase(https://docs.angularjs.org/api/ng/filter/uppercase)
some syntax errors
But seems that access by dynamic object key inside ng-repeat works pretty correct
https://jsbin.com/rodecosoyo/1/edit?html,js,output
Angular Application
var app = angular.module('arrayid', []);
app.controller('arrayContainerCtrl', function($scope) {
$scope.diagnosis = {
mainfractures: [{
id: "metacarpal",
textinput_id: "metacarpal_text",
title: "5th Metacarpal",
}, {
id: "proximal_phalanx",
textinput_id: "proximal_phalanx_text",
title: "Proximal Phalanx",
}, {
id: "middle_phalanx",
textinput_id: "middle_phalanx_text",
title: "Middle Phalanx",
}, {
id: "distal_phalanx",
textinput_id: "distal_phalanx_text",
title: "Distal Phalanx",
}, {
id: "scaphoid_fracture",
textinput_id: "scaphoid_fracture_text",
title: "Scaphoid Fracture",
}]
};
$scope.checklists = {
"diagnosis": {
metacarpal: ['1', '2'],
proximal_phalanx: ['2', '3'],
middle_phalanx: ['3'],
distal_phalanx: ['4'],
scaphoid_fracture: ['5']
}
};
});
Markup:
<body ng-app='arrayid' ng-controller='arrayContainerCtrl'>
<div ng-repeat="fracture in diagnosis.mainfractures">
<h4>{{ fracture.title }}</h4>
<div class="row">
<ul type="disc">
<li ng-repeat="selection in checklists['diagnosis'][fracture.id]">
• {{ selection | uppercase }}
</li>
</ul>
</div>
</div>
</body>

How to bind the JSON object data to knockout binding with template option?

I am working with knockout js. Now i am using template option and local json data as datasource.In this i am unable to bind the data to node within template.
Please get my html code below:
<div data-bind="template:{name:'treeTemplate',data:{da:Data}}"></div>
<script id="treeTemplate" type="text/html">
<b data-bind="text:$data.text"></b>
Please get my script section below
var treeData = [
{ id: 1, text: "UK"},
{ id: 2, text: "Steven John" },
{ id: 3, text: "USA" },
{ id: 5, text: "Andrew" },
{ id: 4, text: "Angelica" }
];
window.viewModel = {
value: ko.observable(new Date(2015, 06, 15)),
Data: ko.observableArray(treeData)
};
$(function () {
// declaration
ko.applyBindings(viewModel);
});
I have updated the sample in jsfiddle also. Please get the below link:
https://jsfiddle.net/38vnznht/
Can you please anyone suggest on this.Thanks for any help.
your first problem is the use of data in the template object.
data:{da:Data}
for iterating through a array you need to use foreach
foreach:data
so because of this you need to update your bindings
// from this
<b data-bind="text:$data.text"></b>
// to this
<b data-bind="text: text"></b>
here is a working example :
https://jsfiddle.net/wqe3s1vs/3/
Also, documentation on using "foreach" with a named template :
http://knockoutjs.com/documentation/template-binding.html#note-2-using-the-foreach-option-with-a-named-template

Getting a a.foreach is not a function error

I am trying to build a multiselect list using angular js. I am getting a weird TypeError: a.foreach is not a function and I can’t seem to figure out when.
js :
var myAppModule = angular.module('multiselect', []);
myAppModule.controller("view", function ($scope) {
$scope.listA = {
values: [{
id: 1,
label: 'aLabel',
subItem: {
name: 'aSubItem'
}
}, {
id: 2,
label: 'bLabel',
subItem: {
name: 'bSubItem'
}
}],
selected: {
name: 'aSubItem'
}
};
})
html:
<select multiple ng-options="item.subItem as item.label for item in listA.values track by item.id" ng-model="listA.selected"></select>
I don’t know what I could be doing wrong. Am I casting something wrong ?
The problem is that since you have added the multiple attribute, the value of the select should be an array. So try something similar to this:
$scope.listA = {
values: [{
id: 1,
label: 'aLabel',
subItem: {
name: 'aSubItem'
}
}, {
id: 2,
label: 'bLabel',
subItem: {
name: 'bSubItem'
}
}],
selected: [{
name: 'aSubItem'
}]
};
You need not to track your values by id. it will do it by default.
<div ng-controller="Main">
<select multiple ng-options="item.subItem as item.label for item in listA.values" ng-model="listA.selected"></select>
</div>
JS Fiddle for your code (Fix):
http://jsfiddle.net/juag4okg/
I was having the same problem. It worked well by creating the static json object as answered above, but did not worked out when i tried to fetched the object or list from the server.
Then i realized my server was not sending the json object and i hadn't convert it to json as well. And when i converted it to json it worked perfectly fine.
So if you are having similar problem to display the select options (muliple or single) from the server side data this process might help you.
here is the link to angular angular.toJson() function.

Angularjs map array to another array

I have two arrays, Users and Employments like so:
Users = [{id:1, name: "ryan"}, {id:2, name:"Julie"}]
Employments = [{user_id: 1, title: "manager"}, {user_id: 2, title: "Professor"}]
I'd like to display the Employments array in an ng-repeat like so:
<li ng-repeat="employment in Employments">
{{employment.user.name}}
</li>
How do I map the Users array to the Employments array?
If you want the employee name to get displayed based on id, the simplest way is just pass that id to a function and return the name, like as shown below
Working Demo
html
<div ng-app='myApp' ng-controller="ArrayController">
<li ng-repeat="employment in Employments">{{getEmployeeName(employment.user_id)}}
</li>
</div>
script
var app = angular.module('myApp', []);
app.controller('ArrayController', function ($scope) {
$scope.Users = [{
id: 1,
name: "ryan"
}, {
id: 2,
name: "Julie"
}];
$scope.Employments = [{
user_id: 1,
title: "manager"
}, {
user_id: 2,
title: "Professor"
}];
$scope.getEmployeeName = function (empId) {
for (var i = 0; i < $scope.Users.length; i++) {
if ($scope.Users[i].id === empId) {
return $scope.Users[i].name;
}
};
};
});
UPDATE 2
If you want to embed the User array in the Employments array, try the following stuff
$scope.Users = [{id: 1, name: "ryan"}, {id: 2, name: "Julie"}];
$scope.Employments = [{user_id: 1, title: "manager"},
{user_id: 2, title: "Professor"}
];
code for flattening Employments array by adding User properties
angular.forEach($scope.Users, function (user, userIndex) {
angular.forEach($scope.Employments, function (employee, employeeIndex) {
if (employee.user_id === user.id) {
employee.name = user.name;
}
});
});
Output
$scope.Employments = [ { user_id: 1, title: "manager", name: "ryan" },
{ user_id: 2, title: "Professor", name: "Julie" }
]
Working Demo
UPDATE 3
Code for making a nested employee structure like as shown below from $scope.Users and $scope.Employments
$scope.employees = [];
angular.forEach($scope.Employments, function (employee, employeeIndex) {
var employeeObject = {};
employeeObject.title = employee.title;
angular.forEach($scope.Users, function (user, userIndex) {
if (employee.user_id === user.id) {
employeeObject.user = user;
}
});
$scope.employees.push(employeeObject);
});
Output
[ { title: "manager", user: { "id": 1, "name": "ryan" } },
{ title: "Professor", user: { "id": 2, "name": "Julie" } }
]
Working Demo
If you wanted to match up the two following arrays purely with a template you could take the following arrays
Users = [{id:1, name: "ryan"}, {id:2, name:"Julie"}]
Employments = [{user_id: 1, title: "manager"}, {user_id: 2, title: "Professor"}]
And nest a repeat like:
<li ng-repeat="employment in Employments">
<div ng-repeat="user in Users" ng-if="user.id === employment.user_id" >
{{user.name}}:{{employment.title}}
</div>
</li>
Two more nice little thing to do to avoid any risk of getting those brackets showing on a slow page load is to use the ng-bind and prefix the attributes with data so its with the html spec
<li data-ng-repeat="employment in Employments">
<div data-ng-repeat="user in Users" data-ng-if="user.id === employment.user_id" >
<span data-ng-bind="user.name"></span>:<span data-ng-bind="employment.title"></span>
</div>
</li>
I know you didn't have the need for anything but the name, but figured a quick example of using the outer loop in the inner still could be helpful. Also this would be the case for ng-init if you needed to reference the the $index of the outer ng-repeat from the inner, but that might be more than you're looking for here.
Plunker
This sorts the users names into the employments array:
var sortUsers = function() {
var i = 0;
for (i; i < $scope.users.length; i++) {
console.log($scope.users[i].id)
for(var z = 0; z < $scope.employments.length; z++) {
if($scope.employments[z].user_id === $scope.users[i].id) {
$scope.employments[z].name = $scope.users[i].name;
}
}
}
}
HTML:
<ul>
<li ng-repeat="employment in employments">
{{employment.name}}
</li>
</ul>
I dealt similar problem yesterday. If you want to use js, have to loop twice.
I recommend to use the best way is to select in one query by join table if data come from single database.
You select User by one query, and Employment for another query in database. Then, twice ng-repeat to re-arrange. Here is my solution.
select users.*, employments.title from `users` inner join `employments` where users.id = employments.user_id;
Hope be be helpful.

Categories

Resources