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);
Related
I have the following json file in ReactJS:
{
"locations": [
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501
"loc": "NEW YORK STATE"
}
]
}
How can I get the value of a an element where the id=xxxx? Also how can I get the loc when id=xxxx?
you can use underscorejs
let array_of_ids = _.pluck(json_object.locations,"id")
//now find the index of your particular id
let index = _.indexOf(array_of_ids,yourId)
//now your required object is
let your_object = json_object.locations[index]
Thats it
cheers
You can use the filter function.
var obj = {
"locations": [
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501,
"loc": "NEW YORK STATE"
}
]
}
var val = '8817';
var res = obj.locations.filter(function(item) {
return item.id == val;
});
console.log(res[0].loc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
I need to access the values of "city" and "nation" inside the array the following json file using AngularJS with ng-repeat.
This is my Json file:
[
{
"name": "first",
"location": [
{
"city" : "milan",
"nation" : "italy"
}
],
"visibility": 1
},
{
"name": "second",
"location": [
{
"city" : "new york",
"nation" : "usa"
},
{
"city" : "london",
"nation" : "uk"
}
],
"visibility": 1
}
]
My problem is that I need to get City and Nation as text string values, because I need to add them as css class name inside a tag, basically like this:
<div class="milan italy"></div>
<div class="new york usa london uk></div>
I'm not able to figure it out how to do this.
I tried with this code but nothing is shown:
<div ng-repeat-start="tile in tiles"></div>
<div class="mix {{ tile.location.city }} {{ tile.location.nation }}"></div>
<div ng-repeat-end></div>
Thank you in advance for your suggestions.
As #MattDionis said, you would need to specify ng-class, not just class. What you can try is using a function for ng-class. So you can do
<div ng-repeat="tile in tiles">
<div ng-class="getLocation(tile)"></div>
</div>
$scope.getLocation = function(tile) {
var resp = '';
for (var i = tile.location.length; i-- > 0;) {
resp = resp + tile.location[i].city + ' ' + tile.location[i].nation;
}
return resp;
}
I'm sure there's a better way to combine them than that, but that's what I came up with off-hand
First, you want to use ng-class rather than simply class to properly evaluate those bindings.
Also, tile.location appears to be an array of objects rather than simply an object. Therefore, {{ tile.location.city }} would not work, but {{ tile.location[0].city }} should.
The remaining issue would be how to loop through mutliple city/nation values within ng-class. I'll get back to you on that.
Please see demo below
You can create function to transform your array of object to string ie:
$scope.tostring = function (array) {
var res = "";
angular.forEach(array, function (obj) {
console.log(obj);
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
res += " " +obj[k];
}
}
});
return res;
};
var app = angular.module('app', []);
angular.module('app').controller('homeCtrl', homeCtrl);
homeCtrl.inject = ['$scope'];
function homeCtrl($scope) {
$scope.titles = [{
"name": "first",
"location": [{
"city": "milan",
"nation": "italy"
}],
"visibility": 1
}, {
"name": "second",
"location": [{
"city": "new york",
"nation": "usa"
}, {
"city": "london",
"nation": "uk"
}
],
"visibility": 1
}];
$scope.tostring = function(array) {
var res = "";
angular.forEach(array, function(obj) {
console.log(obj);
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
res += " " + obj[k];
}
}
});
return res;
};
}
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="homeCtrl">
<div ng-repeat="title in titles">
<h3 ng-class="tostring(title.location)">{{title.name}} My class is:*{{tostring(title.location)}}* </h3>
</div>
</body>
</html>
I have a json something like this
{
"count": 67,
"0": {
"id": "2443",
"name": "Art Gallery",
"category": {
"id": "2246",
"name": "Gifts & Memories"
},
"deckLocation": [
{
"id": "2443",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
}
]
},
"1": {
"id": "7198",
"name": "Captain's Circle Desk",
"category": {
"id": "352",
"name": "Other Services"
},
"deckLocation": [
{
"id": "7198",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
},
{
"id": "7198",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
}
]
}
}
I want to display all names which is inside the "0", "1" array. I can able to list a specific name but not all. The fist name will display which I written in the following code. But I need to display all 0, 1, 2, 3 etc names dynamically.
data[0].name
Please help me.
Thank you.
use ng-repeat function to do so.
<div ng-repeat = "names in data">
<P>{{names.name}}</P>
</div>
Let us say you have a service like this:-
var todoApp = angular.module("todoApp",[]);
todoApp.factory('dbService', ['$q','$http',function ($q , $http) {
var service ={};
service.getUrl = function (urlToGet) {
var svc=this;
var deferred = $q.defer();
var responsePromise = $http.get(urlToGet);
responsePromise.success(function (data, status, headers, config) {
deferred.resolve(data); });
responsePromise.error(function (data, status, headers, config) {
deferred.reject({ error: "Ajax Failed", errorInfo: data });});
return (deferred.promise);
}
return service;
}]);
And you want to load a file named '/js/udata.json'. Here is how in you controller you can load this file:-
todoApp.controller("ToDoCtrl", ['$scope','$timeout','dbService',function($scope, $timeout, dbService)
{
$scope.todo={};
$timeout(function(){
dbService.getUrl('/js/udata.json').then(function(resp){
$scope.todo=resp;
});},1);
};
Hope this helps!
You have data[0].name right?
then why don't you loop through that to get all the name elements in those arrays.
like...
for(i=1;i<data.length;i++)
{
console.log(data[i].name);
}
I have a collection of items. The items are broken down into "types" and then further divided within the type into "categories". I do not know the names of the "types" or the "categories" before hand.
I would like to do some nested foreach binding to represent the data hierarchically. Something like this:
<ul data-bind="foreach: OrderItems.Types">
<li>
ItemType: <span data-bind='text: $data'></span>
<ul data-bind="foreach: Categories">
<li>
Category: <span data-bind='text: $data'></span>
<ul data-bind="foreach: OrderItems">
<li>
Item: <span data-bind="text: Name"> </span>
</li>
</ul>
</li>
</ul>
</li>
var order = {
"OrderNumber": "394857",
"OrderItems": {
"Types": {
"Services": {
"Categories": {
"carpet cleaning": {
"OrderItems": [
{
"OrderItemID": "9d398f88-892c-11e3-8f31-18037335d26a",
"Name": "ARug-Oriental Rugs (estimate on site)"
},
{
"OrderItemID": "9d398f53-892c-11e3-8f31-18037335d26a",
"Name": "C1-Basic Cleaning (per room)"
},
{
"OrderItemID": "9d398f54-892c-11e3-8f31-18037335d26a",
"Name": "C2-Clean & Protect (per room)"
},
{
"OrderItemID": "9d398f55-892c-11e3-8f31-18037335d26a",
"Name": "C3-Healthy Home Package (per room)"
}
]
},
"specialty": {
"OrderItems": [
{
"OrderItemID": "9d398f8f-892c-11e3-8f31-18037335d26a",
"Name": "SOTHR-Other"
}
]
},
"tile & stone": {
"OrderItems": [
{
"OrderItemID": "9d398f8e-892c-11e3-8f31-18037335d26a",
"Name": "TILE-Tile & Stone Care"
}
]
},
"upholstery": {
"OrderItems": [
{
"OrderItemID": "9d398f7b-892c-11e3-8f31-18037335d26a",
"Name": "U3S1-Upholstery - Sofa (Seats 3: 7 linear feet)"
},
{
"OrderItemID": "9d398f7c-892c-11e3-8f31-18037335d26a",
"Name": "U3S2-Upholstery - Sofa - Clean & Protect (Seats 3: 7 linear feet"
}
]
}
}
},
"Products": {
"Categories": {
"carpet cleaning": {
"OrderItems": [
{
"OrderItemID": "9d398f84-892c-11e3-8f31-18037335d26a",
"Name": "PLB-Leave Behind Item"
}
]
}
}
}
}
}
};
var viewModel = ko.mapping.fromJS(order);
ko.applyBindings(viewModel);
here's a fiddle with the above code: http://jsfiddle.net/mattlokk/6Q5f7/5/
To bind against your structure, you would need to turn the objects into arrays. Given that you are using the mapping plugin, the easiest way would likely be to use a binding that translates an object with properties to an array of key/values.
Here is a sample binding:
ko.bindingHandlers.objectForEach = {
init: function(element, valueAccessor, allBindings, data, context) {
var mapped = ko.computed({
read: function() {
var object = ko.unwrap(valueAccessor()),
result = [];
ko.utils.objectForEach(object, function(key, value) {
var item = {
key: key,
value: value
};
result.push(item);
});
return result;
},
disposeWhenNodeIsRemoved: element
});
//apply the foreach bindings with the mapped values
ko.applyBindingsToNode(element, { foreach: mapped }, context);
return { controlsDescendantBindings: true };
}
};
This will create a computed on-the-fly that maps the object to an array of key/values. Now you can use objectForEach instead of foreach against your objects.
Here is a basic sample: http://jsfiddle.net/rniemeyer/nn3jg/ and here is an example with your fiddle: http://jsfiddle.net/rniemeyer/47Wbe/
I'm trying to create a nested listed view with jQuery. The data is in a json file.
Looks like this:
{
"fakultaeten": [
{
"id": "1",
"name": "Carl-Friedrich Gauß",
"institut": [
"Mathematik",
"Informatik"
]
},
{
"id": "2",
"name": "Lebenswissenschaften",
"institut": [
"Biologie/Biotechnologie",
"Chemie/Lebensmittelchemie"
]
},
{
"id": "3",
"name": "Architektur, Bauingenieurwesen und Umweltwissenschaften",
"institut": [
"Department Architektur",
"Department Bauingenieurwesen und Umweltwissenschaften"
]
},
{
"id": "4",
"name": "Maschinenbau",
"institut": [
"test"
]
},
{
"id": "5",
"name": "Elektrotechnik, Informationstechnik, Physik",
"institut": [
"Institut für Datentechnik und Kommunikationsnetze",
"Institut für Elektrische Maschinen, Antriebe und Bahnen"
]
},
{
"id": "6",
"name": "Geistes- und Erziehungswissenschaften",
"institut": [
"test"
]
}
]
}
I'm calling the data like this:
<script type="text/javascript" charset="utf-8">
$.getJSON("fakultaeten.js",function(data)
{
$.each(data.fakultaeten, function(key,value)
{
$.each(value.institut, function(key1,value1)
{
//console.log(value1)
}
);
}
);
return false;
}
);
</script>
Now I'm a little confused how to display the data in this HTML code.
<div data-role="content">
<h3>Institut für Nachrichtentechnik</h3>
<ul id="taskList" data-role="listview"></ul>
</div>
I know it's a basic problem, but all the other questions and tutorials I found are really confusing me.
I want the nested list look like in this demo: http://jquerymobile.com/demos/1.2.1/docs/lists/lists-nested.html#&ui-page=2-4
it's very simple: just put list value inside the list with id taskList:
<script type="text/javascript" charset="utf-8">
$.getJSON("fakultaeten.js",function(data)
{
var list = $('#taskList');
$.each(data.fakultaeten, function(key,value)
{
var mother = "<li>"+value.name+"<ul>";
$.each(value.institut, function(key1,value1)
{
var son="<li>"+value1+"</li>";
mother+=son;
}
);
mother+="</ul></li>";
list.append(mother);
}
);
list.listview("refresh");
return false;
}
);
</script>
Thanks to #JackTurky I got the solution. He was almost right.
This is how I solved it in the end.
<script type="text/javascript" charset="utf-8">
$.getJSON("fakultaeten.js",function(data)
{
var list = $('#taskList');
$.each(data.fakultaeten, function(key,value)
{
var mother = "<li>"+value.name+"<ul>";
$.each(value.institut, function(key1,value1)
{
var son="<li>"+value1+"</li>";
mother+=son;
}
);
mother+="</ul></li>";
list.append(mother);
}
);
list.listview("refresh");
return false;
}
);
</script>