I'm learning how to use onsen.io and the best way to learn is by making a Pokemon app!
But of course, being a noob, I'm having trouble trying to loop through my list of 151 Pokemons using onsen.io. I'm able to console.log the list of 151, but I'm not sure what's missing to display it in an ons-list.
Am I looping it incorrectly?
Thanks!
Here's my code:
<ons-navigator id="myNavigator" page="main-temp"></ons-navigator>
<!-- ******************** main-template ******************** -->
<template id="main-temp">
<ons-page id="main-page">
<ons-toolbar style="background-color: red;">
<div class="center" style="color: #fff;">Pokedex</div>
</ons-toolbar>
</ons-page>
</template>
<!-- ******************** list template ******************** -->
<template id="list-temp">
<ons-page id="list-page">
<div class="content content-container">
<ons-list id="list-item"></ons-list>
</div>
</ons-page>
</template>
<!-- ******************** spinner modal ******************** -->
<ons-modal id="spinner-modal">
<div style="margin: auto;">
<ons-icon icon="md-spinner" size="100px" spin></ons-icon>
</div>
</ons-modal>
window.onload = function (){
var spinnerModal = document.querySelector('#spinner-modal');
spinnerModal.show();
var settings = {
"url":`https://pokeapi.co/api/v2/pokemon?limit=151`,
"method": "GET",
"timeout": 0,
};
$.ajax(settings)
.done(function(result){
sendData(result);
let results = result;
console.log(results);
})
.fail(function(xhr, status, error){
console.log('error:' + xhr.status);
})
.always(function(){
spinnerModal.hide();
})
function sendData(jsonData){
var itemsList = document.getElementById('list-item');
for(let i = 1; i < jsonData.length; i++){
itemsList.appendChild(
ons.createElement(
'<ons-card class="inside-cards">'+
'<ons-list>' +
'<ons-list-item modifier="tappable>' +
'<div class="left" >' +
jsonData[i].name +
'</div>' +
'<div class="" style="margin-left:20px;" >' +
'<ons-icon icon="fa-hashtag"></ons-icon>' + ' ' + jsonData[i].name + "<br><br>" +
'<ons-icon icon="fa-thumbs-up"></ons-icon>' + ' ' + jsonData[i].name + "<br><br>" +
'<ons-icon icon="fa-user"></ons-icon>' + ' ' + jsonData[i].name + "<br><br>" +
'</div>' +
'<div>' +
'</div>' +
'</ons-list-item>' +
'</ons-list>' +
'</ons-card>'
)
);
}
}
}
there are two problems in your code.
resultbut you want list of pokemons which is avaialble inresult.resultsso you need to callsendData(result.results)templatetag which creates a different document scope calleddocumentFragment. also in template the id means the HTML page you want to render in app as template so id should be defined asid='something.htm'. for more details read ons-templateproper use of template
showing this in online editor is a bit difficult since online editor provide only one HTML. let me see if I get time to do this in plunkr/stackblitz online editor or I hope you figure out this from
ons documentation.