How can i hard code my data from realtime database? - javascript

So i have some data stored in a realtime datastore and only the admin can access the page where all the data is displayed, but how do i hard code the data to the website this is what i have and tried:
<!-- my html -->
<div v-for="(option, i) in reserveringen" :key="i">
{{ reserveringen[i] }}
</div>
data: function(){
return {
lidnummer: '',
reserveringen: []
}
},
mounted() {
self = this
const reserveringsref = firebase.database().ref('Reserveringen/')
reserveringsref.once('value', function(snapshot){
const lidnummer = ''
const reserveringen = []
snapshot.forEach(function(childSnapshot){
const data = childSnapshot.val()
self.lidnummer = data.Lidnummer
reserveringen.push(
"<tr><td>" + data.Lidnummer + "</td></tr>"
)
});
self.reserveringen = reserveringen;
});
},
This will only display the array i made as text. Can anyone help me with this issue or am i completely doing this wrong any advice will be thanked!

Your isue is not with RT-db but with Vue i guess;
If you want to build HTML in the JS section (as you do by pushing html tags inside an array), you should use the v-html directive instead of the interpolation.
Something like that
<div v-for="(option, i) in reserveringen" :key="i" v-html="reserveringen[i]">
</div>

Related

Working with html template tag and can't seem to display whole array of information

This is my first time working with the html template tag. I don't know if I am doing it wrong but the output of the template is only showing the last item in the array. I've tried to loop through it and the foreach method but still only the last item shows. I know I am probably overriding the items as they are stacked on top of each other but I can't seem to figure it out Can someone point me in the right direction?
<div class="products-container">
<template>
<div class="product">
<img class="img">
<h2 class="item-title"></h2>
<h3 class="price"></h3>
</div>
</template>
</div>
const template = document.querySelector('template').content
const copyTemplate = document.importNode(template, true)
let shoppingList = [];
async function getData(data) {
const products = data.items.map(product => {
copyTemplate.querySelector('.item-title').textContent = product.title;
copyTemplate.querySelector('.price').textContent = product.price;
copyTemplate.querySelector('.img').src = product.image;
});
document.querySelector('.products-container').appendChild(copyTemplate);
shoppingList.push(products);
return products
}
I figured it out. I had to put the template and the copytemplate within the map function for it to work.

Feed Outside JS object into Vue.js component

In my JS I have list of products.
var productData = [{
title: 'Bike',
price: 300
},{
title: 'Guitar',
price: 199
}]
This data is gathered from remote Json in a Async call. So I have to do this in JS.
Eventually, I come to a situation, that I need to display this product. But here are 2 things.
1) In HTML I am outside of my main Vue instance scope. It is so because there is 3rd party API that interacts with those products, apart other things... So This array is not bound to Vue instance in any way.
2) This product list is dynamically created, on the fly. In order to display it, I have to do a good old html string concatenation and then apply it.
Main problem:
Now whenever I need to display a product - I have a Vue.js Component for it. That has a template, and all data goes really nicely. I obviously want to reuse this same template.
So right now I have something like this:
//Vue.js Component, that I want to use, and feed my product to:
Vue.component('product', {
props: ['product'],
template: `
<div class="prod">
<h3>{{product.title}}</h3>
<p>{{product.price}} €</p>
</div>
`, data() {
return {
}
}
});
Next in JS, I have this code:
var prodList = getProductsAsync("3rd party service URL and parameters");
var prodHtml = '';
for(var i = 0; i < prodList.length; i++){
prodHtml += `
<div class="prod">
<h3>${prodList[i].title}</h3>
<p>${prodList[i].price} €</p>
</div>
`;
}
Here I have 2 templates (one as JS html, and another in Vue.js component), that is redundant.
I need to have 1 way to maintain this template. At the moment template is simple, but more functionality will shortly come.
Idealy I would like my JS object to use my Vue.js template. As a result it would also behave as Vue.js component too.
So in my JS I would like to have it like this (But this obviously does not work):
var prodList = getProductsAsync("3rd party service URL and parameters");
var prodHtml = '';
for(var i = 0; i < prodList.length; i++){
prodHtml += ` <product :product='prodList[i]'></product>`; // attempt to use Vue.js component 'on the fly' but this does not work!
}
Any suggestions?
It doesn't work, because there is some order in which you have to create component, html, and Vue instance.
// just use all your code together
// first, prepare the component
Vue.component('product', {
props: ['product'],
template: `
<div class="prod">
<h3>{{product.title}}</h3>
<p>{{product.price}} €</p>
</div>
`
})
// and get products
var prodList = getProductsAsync('/someMountpoint')
// then generate html with unknown tags "product"
var prodHtml = '<div id="productList">'
for(let i = 0; i < prodList.length; i++) {
prodHtml += `<product :product='prodList[i]'></product>`
}
prodHtml += '</div>'
// append this html to DOM
$('#someWhere').html(prodHtml)
// and now create new Vue instance to replace
// these unknown product tags with real tags
new Vue({
el: '#productList'
})

Fail to access DOM element in Vue component when using generic javascript

I am trying to dynamic to update data from Vue.compnent by using jQuery way on Webpack project. following is code snippet.
<template>
<div id="container">
<slot>show string!!</slot>
<div id="s_container"></div>
</div>
</template>
<script>
export default {
}
const items = [
'thingie',
'anotehr thingie',
'lots of stuff',
'yadda yadda'
]
function listOfStuff () {
let full_list = ''
for (let i = 0; i < items.length; i++) {
full_list = full_list + '<li>{{items[i]}}</li>'
}
// const contain = document.querySelector('#s_container')
const contain = this.$el.querySelector('#s_container')
if (contain != null) {
contain.innerHTML = '<ul ${full_list} </ul>'
} else {
console.log('contain is null');
}
}
listOfStuff()
</script>
but this contain variable is always fail to get #s_container element. How can I get it correctly from outside java script?
Thanks.
First you need to bind your items array into a data return function like this:
export default {
data()
return {
items: ['thingie', 'yadda yadda']
}
}
Then you can use a v-for loop the display this array into a HTML li.
Like this into your template:
<template>
<div>
<ul>
<li v-for="(item, index) in items" :key=index>
{{ item }}
</li>
</ul>
</div>
</template>
In this way you can render a simple list using vue.js, if you need more informations about this feature read this part of the documentation: https://v2.vuejs.org/v2/guide/list.html
Have a good day !

Retrieve Firebase database specific value depending on key with angular 5

as the title says I build a CRUD application using Angular 5 and CRUD works just fine but now I need to retrieve a specific post data with advanced routing so the url should be something like :
https://example.com/blog/howtoDoSomething
and the page should contain this post details like name, content , image and so on .
I tried
details.component.ts
this.sub = this.route.params.subscribe(params => {
this.key = params['$key'];
});
details.component.html
<p>
this page about {{ $key }}
</p>
the above code worked fine with angular 4 with some difference of course and I used a json file not Firebase .
I also tried this one :
details.component.ts
var x = this.blogService.getData();
x.snapshotChanges().subscribe(item => {
this.blogList = [];
item.forEach(element => {
var y = element.payload.toJSON();
y["$key"] = element.key;
this.blogList.push(y as Blog);
});
});
details.component.html
<div *ngFor="let blog of blogList">
{{blog[$key].title}}
</div>
this one if I use blog alone like :
<div *ngFor="let blog of blogList">
{{blog}}
</div>
this retrieves the whole database as as
[object object] repeated
thanks in advance .
// user-service.ts
public getUser(userId: string) {
return this.afs.doc('users/' + userId).valueChanges();
)
// user-component.ts
// Get userId from route
this.user$ = this.userService.getUser(userId);
// user-component.html
<div *ngIf="user$ | async as user">
{{user | json}}
</div>

ng-repeat not rendering data from array

I am working on a web app where non-profit organizations can create a profile and be easily searchable by various parameters. In the "create and organization" form, I have a nested array where the organization can add donations that they need. The array is storing ok (I can add multiple donations), however when I try to display it using ng-repeat, nothing renders. When I don't use the ng-repeat and just display via {{ ctrl.organization.donations }} the information shows up with brackets and quotation marks.
Here is the code that I use to add the donations (via the newOrganization controller):
function NewOrganizationController(OrganizationService, CategoryService, $stateParams, $state, $http, Auth){
var ctrl = this;
CategoryService.getCategories().then(function(resp) {
ctrl.categories = resp.data;
});
ctrl.donations = [{text: ''}];
Auth.currentUser().then(function(user) {
ctrl.user = user;
})
ctrl.addNewDonation = function() {
var newDonation = ctrl.donations.length+1;
ctrl.donations.push({text: ''});
};
ctrl.removeDonation = function() {
var lastItem = ctrl.donations.length-1;
ctrl.donations.splice(lastItem);
};
ctrl.addOrganization = function() {
var donations = this.donations;
var allDonations = [];
for (var key in donations) {
if (donations.hasOwnProperty(key)) {
var donation = donations[key].text;
allDonations.push(donation);
}
}
var data = {
name: ctrl.organization.name,
description: ctrl.organization.description,
address: ctrl.organization.address,
donations: allDonations.join("/r/n"),
category_id: this.category.id
};
OrganizationService.createOrganization(data);
$state.go('home.organizations');
};
}
angular
.module('app')
.controller('NewOrganizationController', NewOrganizationController);
Here is the code that I am using to display the array on my show page (this is what shows up with brackets, i.e. donations needed: ["food", "clothing"]):
<h5>{{ ctrl.organization.donations }}</h5>
This is the ng-repeat code that is not rendering anything to the page:
<li class="list-group-item" ng-repeat="donation in donations track by $index">
{{ donation }}
</li>
I've tried to use .join(', ') within the {{donation}} brackets, but this isn't recognized as a function.
edit: After taking AJ's suggestion here is a screenshot of what appears...anyone know how to fix this?
seems that my array is showing up in table form, with each row containing one character
Any help would be greatly appreciated. Here is a link to the github repo in case you want to look at anything else or get a bigger picture.
You need to use the same variable name that works in the h5
<li class="list-group-item" ng-repeat="donation in ctrl.organization.donations track by $index">
{{ donation }}
</li>

Categories

Resources