The data from records comes as shown (template) : {"Id":750,"Name":"Juaquin","Nationality":"American"} I would like to pass the information on Nationality to a function called flagUrl(someData) that gets the Nationality and returns a path of a URL of a Country Flag.
self.flagUrl = ko.computed(function(data){
var obj = data;
var c = countries.filter((country) => country.Nationality === obj)[0].alpha_2_code;
//console.log(c);
var alpha2code = c;
myPath = "https://countryflagsapi.com/png/" + alpha2code;
return myPath;
}, self);
and I would like to insert it throughout the HTML like this:
<tbody data-bind="foreach: records">
<tr>
<td class="align-middle" data-bind="text:DriverId"></td>
<td class="align-middle" data-bind="text:Name"></td>
<td class="align-middle" data-bind="text:Nationality"></td>
<td><img src="" alt="" height=25px width=40px data-bind="attr:{src: $root.flagUrl($Nationality)}"></img></td>
<td class="text-end">
<a class="btn btn-default btn-light btn-sm" data-bind="attr: { href:'./driverDetails.html?id=' + DriverId }"><i class="fa fa-address-card-o" title="Selecione para ver detalhes"></i></a>
</td>
</tr>
</tbody>
I'm using knockout.js for binding. The function in flagUrl is correct and does as it is told, it just doesn't work when the data comes from the HTML. I'm in desperation. I've been dueling with this for the past few days. Thank you in advance
This doesn't implement the flags in exactly the way you were thinking (with a function call) but this might be an acceptable alternative.
Here's a working example: https://jsfiddle.net/galeroy/k9ro26nj/10/
<!DOCTYPE html>
<head>
<title>KnockoutJS Flags</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type = "text/javascript"></script>
</head>
<body>
<table data-bind="foreach: records">
<tbody>
<tr>
<td class="align-middle" data-bind="text: DriverId"></td>
<td class="align-middle" data-bind="text: Name"></td>
<td class="align-middle" data-bind="text: Nationality"></td>
<td>
<img data-bind="attr: { src: 'https://countryflagsapi.com/png/' + Nationality}" height="25" width="40" />
</td>
<td class="text-end">
<button class="btn btn-default btn-light btn-sm" data-bind="attr: { href:'./driverDetails.html?id=' + DriverId }">
<i class="fa fa-address-card-o" title="Selecione para ver detalhes">Selecione para ver detalhes</i>
</button>
</td>
</tr>
</tbody>
</table>
<script src="knockout-demo.js"></script>
</body>
</html>