jquery template array inside of array - arrays

I've a json object like this
[Object]
0: Object
domains: Array[1]
0: "domain1.com"
length: 1
__proto__: Array[0]
name: "name1"
1: Object
domains: Array[2]
0: "domain2.com"
length: 1
__proto__: Array[0]
name: "name2"
These objects are generated on the client and I want to display them by using jQuery.tmpl plugin. I've defined a template to be:
<script id="domain_template" type="text/x-jquery-tmpl">
{{each response}}
{{each response.domains}}
<div class="dummy_copy" data-srvType="${srvType}" data-domain="${domain}">"${value}"</div>
{{/each}}
{{/each}}
</script>
What did i do wrong with it here? thanks

You're code should be:
{{each response}}
{{each $value.domains}}
or
{{each response}}
{{each domains}}
and if you wont to have values: srvType, domain, value they must be members of objects that you store in domains

First of all, i convert to JSON my object like this.
arr = []
for srv in response
for domain in srv.domains
arr.push srvType: srv.srvType, domain: domain
domainTmpl = $.tmpl $(#domainTemplate).template(), arr
After having json object it was rendered by jquery template.This will helpfull for all i think

Related

ion-list display asynchronously added data to array

I am new in ionic. I trying to make an app which will search for Bluetooth devices and will display them.
I have created a service which search for Bluetooth devices. When a device found an event publishes like below:
this.event.publish("ibeacon", newBeacon);
Here is my event injection:
import { Events } from 'ionic-angular/util/events';
......
constructor(private event: Events){}
Here is how I subscribe to the event in order to get the published data:
this.event.subscribe("ibeacon", (newBeacon) => {
this.iBeacons.push(newBeacon);
});
As you can see I have declared an iBeacons Array where I push my received objects. The problem is when I try to display the iBeacons Array contents nothing displayed. Here is how I display my array:
<ion-content padding>
<ion-list>
<ion-item *ngFor="let beacon of iBeacons">
<ion-label>
{{ beacon.hash }}
</ion-label>
</ion-item>
</ion-list>
</ion-content>
The array at the beginning is empty.
I have have checked and I receive correctly my devices when I subscribe to the event.
I don't get errors.
I thing the data is not displayed because the data is added asynchronously in iBeacons array. Any idea?
Here are some of the iBeacons Array contains:
(4) [{…}, {…}, {…}, {…}]
0: {hash: "b5d787ac973341a59bf73838eededcb4", uuid: "fda50693-a4e2-4fb1-afcf-c6eb07647825", major: "10001", minor: "10301", lastFoundTime: 1518003454401}
1: {hash: "50aee081c9833e51ce00b9aa4a0c062d", uuid: "fda50693-a4e2-4fb1-afcf-c6eb07647825", major: "10001", minor: "10206", lastFoundTime: 1518003454391}
2: {hash: "1c8ecafb6efbbc37f905d95551291672", uuid: "fda50693-a4e2-4fb1-afcf-c6eb07647825", major: "10001", minor: "10208", lastFoundTime: 1518003454391}
3: {hash: "442e383d9c582985083b5b05f07161d2", uuid: "fda50693-a4e2-4fb1-afcf-c6eb07647825", major: "10001", minor: "10205", lastFoundTime: 1518003454392}
length: 4
__proto__: Array(0)
Here is the iBeacons array initialization:
iBeacons:any [] = [];
Try to use ChangeDetectorRef like this:
import { ChangeDetectorRef } from '#angular/core';
constructor(private cd: ChangeDetectorRef) {}
this.event.subscribe("ibeacon", (newBeacon) => {
this.iBeacons.push(newBeacon);
this.cd.detectChanges();
});

cant print an object list in html

Object {0: Object, 1: Object, 2: Object, 3: Object, 4: Object, httpStatus: 200, httpStatusText: null, httpBodyText: "[object Object],[object Object],[object Object],[object Object],[object Object]"}
0:Object (example of object i opened to show content)
CountryInitials : "US"
Id: "101"
CountryName: "United States"
Population: 318.9
__proto__:
Object
1:Object
2:Object
3:Object
4:Object
this is an example from my browser that shows how im receiving the data, so its a object that contains objects, and I want to treat it in the html like its an array, and i thought it is but its not working....
this is the html:
<div *ngFor="#obj of myList>
<div><b>Country ID:</b> {{obj.Id}} <b>Country Name:</b> {{obj. CountryName}}}</div>
</div>
and its not working...I dont know why, i just want to present a list of the objects with country id and country name..
the EXCEPTION:
EXCEPTION: Error trying to diff '[object Object]' in [myList in EntityBulkCmp#32:31]
could someone please help me figure this out?
thanks!
You can use the pipe json to print an object inside the template: https://angular.io/docs/ts/latest/api/common/index/JsonPipe-pipe.html
#Component({
selector: 'json-pipe',
template: `<div>
<p>Without JSON pipe:</p>
<pre>{{object}}</pre>
<p>With JSON pipe:</p>
<pre>{{object | json}}</pre>
</div>`
})
export class JsonPipeComponent {
object: Object = {foo: 'bar', baz: 'qux', nested: {xyz: 3, numbers: [1, 2, 3, 4, 5]}};
}
The Exception says items in myList are not unique. Probably you have some repeated elements.
Angular needs to keep track of which item it is enumerating.
Use trackBy option, find the syntax below
<li *ngFor="let item of items; let i = index; trackBy: trackByFn">...</li>
refer https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html for complete usage of the directive.
you can use key and value to print the json format...
In which key is 0, 1, etc (as in your case) and value is object (as in your case)...

extracting information from array using knockout

I currently have an array being passed into my function and i wanted to pull out the information from the array so i can display it on the page.
This is what the array looks like:
EducationalClasses:[object, object]
first object contains:
classId: "324342",
className: "English 101"
second object contains:
classId: "231243",
className: "Reading"
when i do educationalClasses[0] i get the results as in first object. I wanted to create some sort of loop so that in my view page when i have:
<!-- ko foreach: educationalClasses -->
<div data-bind="text: className></div>
<!--/ko-->
i would get English 101 and Reading displayed
This is what i have for my viewModel:
viewModel = function(educationalClasses){
....
self.className= ko.observable(educationalClasses.className); // what i want
}
How can i do this properly and so that all the items in the array are displayed without me having to use educationalClasses[0].className...educationalClasses[1].className
Technically, you don't need any observables for what you're doing here. You just need your viewmodel to have a member named educationalClasses that is an array (or observableArray). You can just wrap your raw data in an object, label it, and it goes.
If you want to change the array and have the view show the updates, you'll want an observableArray. If you want changes to the individual data items to show, you'd want them to be observables as well.
rawData = [{
classId: "324342",
className: "English 101"
}, {
classId: "231243",
className: "Reading"
}];
viewModel = function(educationalClasses) {
return {
educationalClasses: educationalClasses
};
};
ko.applyBindings(viewModel(rawData));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<!-- ko foreach: educationalClasses -->
<div data-bind="text: className"></div>
<!--/ko-->

get not retrieving name attribute from object

From the backbone docs
getmodel.get(attribute)
Get the current value of an attribute from the model. For example: note.get("title")
I seeded some data with a name for each country into a Rails app
Country.create!(name: "Brazil")
Country.create!(name: "France")
Country.create!(name: "Germany")
Country.create!(name: "Spain")
In the console, I created a new collection and fetched the data
countries.fetch();
Object
XHR finished loading: "http://localhost:3000/countries".
Checked the length. Equal to the four countries I created.
countries.length
4
Selected a random one using underscore's shuffle method.
c = countries.shuffle()[0]
The object has a name
Backbone.Model
_changes: Array[2]
_currentAttributes: Object
_events: Object
_hasComputed: false
_previousAttributes: Object
attributes: Object
country: Object
created_at: "2013-01-07T06:09:43Z"
id: 2
name: "France"
updated_at: "2013-01-07T06:09:43Z"
__proto__: Object
__proto__: Object
Tried to get the name attribute from the object several different ways, all without success
c.get('name')
undefined
c.get("name");
undefined
c.get("name")
undefined
Can anyone think what I might be doing wrong?
One thing that I find unusual is that there is a 'country' attribute wrapping the other attributes
attributes: Object
country: Object
created_at: "2013-01-07T06:09:43Z"
id: 2
name: "France"
updated_at: "2013-01-07T06:09:43Z"
I'm not sure why 'country' is wrapping the other data. Is it because I created the seed data with a Country model?
Country.create!(name: "Brazil")
anyways, obj.get('country') doesn't return undefined
c = countries.shuffle()[0]
k = c.get('country')
Object
created_at: "2013-01-07T06:09:43Z"
id: 3
name: "Germany"
updated_at: "2013-01-07T06:09:43Z"
__proto__: Object
but I can't do a get on the name after that (i.e after I did the get on country)
k = c.get('country')
Object
k.get('name')
undefined
Is there a way to remove the country wrapper and just be able to do get on the attributes that it was created with?
Override model.parse to extract the country element. Backbone calls parse before populating the model from fetched data:
var Country = Backbone.Model.extend({
parse: function(attributes) {
return attributes.country;
}
});

How to reference JSON attributes with a period in their name from underscore.js javascript template library

I am using underscore template engine (as part of Backbone.js) and have an issue where an attribute of the JSON object has a period in it i.e.
{
"id": 1234,
"company.id": 4321
}
When I try to access this in the underscore template I get a JavaScript error:
Company ID: <#= company.id #>
I'm wondering if it's possible and how it's done to access attributes with period in them. I'm not in a position to change the generation of the JSON.
cowper
An easy way around that is to wrap another object around it so that you can use [] to access 'company.id'. For example, your template could look like this:
<script id="tmpl" type="text/html">
id: <%= o.id %><br>
company: <%= o['company.id'] %>
</script>​
and your JavaScript like this:
var html = _.template($('#tmpl').html(), {
o: {
"id": 1234,
"company.id": 4321
}
});
Demo: http://jsfiddle.net/ambiguous/wtLkP/1/
​
The Underscore template compiler uses with to supply the context for simple things like <%= x %> in the templates so I don't think you're going to be able to do any better than the o. trick above. Underscore builds a function from your template, you can see the function's source by looking at the source attribute of the function:
var t = _.template(template_source);
console.log(t.source);
That will give you something like this:
function(obj){
var __p='';var print=function(){__p+=Array.prototype.join.call(arguments, '')};
with(obj||{}){
__p+='\n id: '+
( o.id )+
'<br>company: '+
( o['company.id'] )+
' and stuff\n';
}
return __p;
}
and you can see why just <%= [x] %> won't work: with only adjusts the current scope, it can't make [x] into valid JavaScript.

Resources