retrieving images from data return in vuejs - javascript

im trying to display som images in my code , already stored in my data in this way:
<div >
<tr v-for='(ships,index) in destroyedShipBox' :key='index'>
<td>{{ships}}</td>
<div v-for='(links,index1) in destroyedShipBoximages' :key='index1'>
{{links.type==ships?links.src:''}}
</div>
</tr>
</div>
where my data stores this arrays of objects:
data() {
return {
destroyedShipBox:['PatrolBoat','Destroyer'],
destroyedShipBoximages:[
{type:'PatrolBoat',src:require('../assets/patrolBoatHorizontalView.png')},
{type:'Submarine',src:require('../assets/submarineHorizontalView.png')},
{type:'BattleShip',src:require('../assets/battleshipHorizontalView.png')},
{type:'Carrier',src:require('../assets/carrierHorizontalView.png')},
{type:'Destroyer',src:require('../assets/destroyerHorizontalView.png')},
],
}
the destroyedShipBox gets fill automatically with some JSON already fetched then destroyedShipBoximages is just a collection of all type of ships in game as well as a image of its according to its type.
Thus my logic in the html template wants to set an image attuning with the kind of ships i already got in the destroyedShipBox array , but the the final result is this
PatrolBoat /img/patrolBoatHorizontalView.63b25d8d.png----->should be an image instead of this
Destroyer /img/destroyerHorizontalView.396ed25f.png ----->should be an image instead of this
simply the image don't appear...
Any advice about how to solve this problem...
thanks in advance!!!!

you can also ease up your template logic and have only one if condition if there is a 1:1 relation between ships and their images with the following computed property:
computed: {
shipsWithImages() {
return this.destroyedShipBoximages.filter((value) => {
if(this.destroyedShipBox.includes(value.type)) {
return value;
}
})
},
}
Cheers,
ewatch

You should assign links.src to src attribute of img tag like this:
<div>
<tr v-for='(ships,index) in destroyedShipBox' :key='index'>
<td>{{ships}}</td>
<td>
<div v-for='(links,index1) in destroyedShipBoximages' :key='index1'>
<img :src="links.src" v-if="links.type==ships"/>
</div>
</td>
</tr>
</div>

Related

Reload Data with .sort from Dynamic Table with Jquery | JSON | Sort with New Data

I have been trying for a few days that when I use the .sort property the data is eliminated or modified instead of it being reloaded as new lines.
Attach Captures from the code Working
Image1 How work the code when i press the button, this sort to the highest price to lowest but how do you can see in the second image, the code appears up and this not delete the old data
Marked with "X" the data that does not have to show
this fragment is the one that generates the tables dynamically
const mostrarProductos = () => {
$.getJSON(URLJSON, (respuesta) => {
for (let z of respuesta) {
productosv2.push(z);
}
for (let x of productosv2) {
$("#fila").append(`
<tr class="deleteProductos">
<div class="card text-center" style="width: 18rem;" id='btnBorrarCarrito'>
<div class="card-body">
<input type="hidden" id="idProd" value="${x.id}"> </td>
<td class="card-title" id="${x.id}">${x.producto}</h2> </td>
<td class="card-text">$ ${x.precio}</p></td>
<div class="btn-group" role="group" aria-label="Basic mixed styles example">
<td><button type="button" class="btn btn-success" onclick="agregarCarrito(${x.id})">Agregar</button></td>
</div>
</div>
</div>
</tr>
`);
}
$("#fila").fadeIn("5000");
});
};
And this function is what orders them
function respuestaClickExpensive() {
$("#fila").html('');
let productosordenados = productosv2.sort((a, b) => {
if (a.precio > b.precio) {
return -1;
}
if (a.precio < b.precio) {
return 1;
}
return 0;
});
return productosordenados;
}
The one that orders them from smallest to largest is the same only that different signs and names.
As you can see I tried to use a ".html ("")" since previously in another cart attempt it used .innerHtml (Which does not work in this case either, Also the code of the cart is totally different from that moment that it worked for me
)
I tried the following:
$ ("#fila"). empty ();
Make another function to clean with .empty
Use Native JavaScript to generate the code.
$ ("#fila"). remove (); this removes all the content for me but does not regenerate it.
Change the HTML tag "Row" to a previous div which, since the div was not generated again, did not generate it again.
$ ("#fila tr"). remove ();
And some more things that I don't remember right now.
If you can guide me on what I did wrong or any suggestions to fix it, I appreciate it.
If I had to follow a template about posting on StackOverFlow or having chosen or named in a different way, I appreciate your comment since it is my first post
Project notes of possible relevance: The complete code outside of html and css is made with Native JavaScript, Jquery, Ajax, SASS and BootStrap.

Is there a method to implement through data attributes in JavaScript?

I want implement the card content in the card when expanded, I have used the help of JavaScript to implement the title, image, description ,I have used 'data-title' and 'data-type' for displaying title and image respectively which are by the working fine and when I try to implement card description by using data-desc attribute , it is displaying 'undefined'.
Anyone please help me with my code.
My code link: https://codepen.io/Avatar_73/pen/ExyNdMK
const getCardContent = (title, type, desc) => {
return `
<div class="card-content">
<h2>${title}</h2>
<img src="./assets/${type}.png" alt="${title}">
<p>${desc}</p>
</div>
`;
}
<div class="cards">
<div class="card" data-type="html" data-desc="I am HTML">
<h2>HTML5</h2>
</div>
</div>
On line 115, you forgot to pass the desc to your getCardContent function
Change to:
const content = getCardContent(card.textContent, card.dataset.type, card.dataset.desc)
Change your calling method signature from
getCardContent(card.textContent, card.dataset.type)
to
getCardContent(card.textContent, card.dataset.type, card.dataset.desc)
you are not passing the third parameter(card.dataset.desc) in the method thus it is rendering the value as undefined.

How to display the content of an array inside an object in Reactjs

I have a React component. When the user makes a form selection, it retrieves the following object (the content of the object varies depending on the selection made):
Data
jsonObj={
"name":"main",
"type":"meat",
"values":[
["chicken","Roast chicken with vegetables"],
["beef","Beef and Yorkshire pudding"]
]}
Desired results
Here's what I want to display on screen when rendered:
<div>
<label htmlFor="chicken">Roast chicken and vegetables</label>
</div>
<div>
<label htmlFor="beef">Beef and Yorkshire pudding</label>
</div>
My failed attempt!
Object.entries(jsonObj["values"]).map(([val,index]))=>{
return(
<div>
<label htmlFor={val[index][0]}>{jsonSub[key][1]}:</label>
</div>
)
}
The result of this is:
Cannot read property '0' of undefined.
And when I try it in the browser console I get "Uncaught SyntaxError: Malformed arrow function parameter list". Is anyone able to help me get my desired results?!
Many thanks!
Katie
Object.entries method is meant to get array from object, But your "values" is already array, So directly use the map
jsonObj["values"].map(([html, text]) => (
<div>
<label htmlFor={html}>{text}</label>
</div>
));
You don't really need Object.entries(). Simply using .map() on jsonObj.values and accessing on each iteration the current array of elements and showing up e[0] and e[1] for <label>.
Instead you can do it easier like the following:
jsonObj.values.map(e => {
return <div>
<label htmlFor={e[0]}>{e[1]}</label>
</div>
});
See the following example:
const jsonObj = {
"name":"main",
"type":"meat",
"values":[
["chicken","Roast chicken with vegetables"],
["beef","Beef and Yorkshire pudding"]
]}
const result = jsonObj.values.map(e => {
// just returning a template literal for representation
return `<label htmlFor="${e[0]}">${e[1]}</label>`;
});
console.log(result)
I hope this helps!

Render images from Entries in Contenful + Angular app

The issues:
How to I access the includes array so I can get the image url to render the image? (or how to I get the images to render in general)
Why is are my description fields not rendering?
So I have a contentful service that gets all the entries as such:
//get all exhibits
getExhibits(query?: object): Promise<Entry<any>[]> {
return this.cdaClient.getEntries(Object.assign({
include : 2,
content_type: CONFIG.contentTypeIds.exhibit
}, query))
.then(res => res.items);
}
The above function is called in my Gallery component as such:
ngOnInit() {
this.contentfulService.getExhibits()
.then(exhibits => this.exhibits = exhibits);
}
And the data is rendered in the corresponding HTML as such:
<section class="gallery__section" [class.menu--open]="menu.isMenuClosed" *ngFor="let exhibit of exhibits">
<figure>
<img src="{{ exhibit.fields.file.url }}" alt="">
<!-- HOW DO I GET THE IMG URL -->
</figure>
<div class="gallery__text">
<h2 class="gallery__heading">Gallery</h2>
<p class="gallery__title">{{ exhibit.fields.title }}</p>
<h3 class="gallery__artist">{{ exhibit.fields.artist }}</h3>
<p class="gallery_onview">On View</p>
<p class="gallery__dates">{{ exhibit.fields.date }}</p>
<p class="gallery__description" *ngIf="exhibit.fields.description.content[0].content[0].value">{{ exhibit.fields.description.content[0].content[0].value }}</p>
</div>
</section>
Bellow is the JSON of one item the items array:
And here the image that is supposed be part of the above item, but is placed in a different array called includes:
Below is the console.log output of one exhibit:
You don't need to access the includes array. The Contentful SDK will automatically resolve the fields that contain a reference.
For your image issue, I think you're missing the field name for your file field: exhibit.fields.YOUR_FIELD_NAME.fields.file.url
For your description field, I would recommend using ngx-contentful-rich-text to parse the rich text into HTML.

angular scope variable is not visible inside anchor tag

Hello I am newbie to Angular and tried to call a controller method with a hyperlink by following way:
{{item.contractnum}}
Where item.contractnum is a scope variable which is visible when I pull it out from 'a' tag but inside the tag its not visible, also I want to pass it back to controller method getAssetDetail but can't figure out how to accomplish it. Please suggest.
EDIT:
View:
<tbody>
<tr ng-repeat="item in pagedItems[currentPage] ">
<td>contract number {{item.contractnum}} <br /> Serial Number:{{item.serialNum}} </td>
</tr>
</tbody>
Controller:
$scope.getAssetDetail = function (contractNum) {
//My Code Here
}
pagedItems=[{"contractnum":"123", "serialNum":"ABC1" },
{"contractnum":"121", "serialNum":"ABC2" },
{"contractnum":"124", "serialNum":"ABC3" },
{"contractnum":"125", "serialNum":"ABC4" }
]
if you realy have pagedItems like
pagedItems=[{"contractnum":"123", "serialNum":"ABC1" },
{"contractnum":"121", "serialNum":"ABC2" },
{"contractnum":"124", "serialNum":"ABC3" },
{"contractnum":"125", "serialNum":"ABC4" }
]
so you wrong use ngRepeat, because pass to it simple object like pagedItems[0]
{"contractnum":"123", "serialNum":"ABC1" }
so item in this case is 123,ABC1 that realy don't have property contractnum and others
for solving you can use
ng-repeat="item in pagedItems"
or save in pagedItems arrays of object like [[{},...],[{},...],[{},...]]
or use filter like limitTo for select only needed element in pagedItems
If your pagedItems data is meant to be just for one page of data, then you need to change the ng-repeat line to:
<tr ng-repeat="item in pagedItems">
If your pagedItems data is meant to be all the data for every page, then you need to change your pagedItems data structure to be an object with properties for each page number like:
pageItems = {
"1": [{"contractnum": "121"}, ... etc],
"2": [{"contractnum": "131"}, ... etc]
... etc ...
}
or as an array of arrays where the index in the outer array is the page number (or perhaps pagenumber - 1) and the inner arrays are arrays of objects for each page like:
pageItems = [
[{"contractnum": "121"}, ... etc],
[{"contractnum": "131"}, ... etc]
]
Your existing ng-repeat line should then work.

Categories