I'm trying to create a custom repeater function similar to Angular JS's ng-repeat
to iterate over data. I want to do this purely with javascript/ jquery and make use of html data-attributes
.
So for example, let's say I have this html
<tr data-repeat="datas">
<td data-repeat-value="data.name">--</td>
<td data-repeat-value="data.email">--</td>
</tr>
I'm wanting to create a function that's smart enough to see this html and map over however many <tr>
's and <td>
's it needs to and spit out the data correctly.
Without the data-attributes, a js solution would look this
${datas.map(data =>
`<tr>
<td>${data.name}</td>
<td>${data.email}</td>
</tr>`).join("")
}`;
But how would I write the js to make use of the data-attributes
?
I've got a codepen showing the working version without data-attributes
along with a non-working version with data-attributes
.
Any help or guidance will be appreciated!
Here is the solution:
getApiData(url, function(apidata){
const $template = $('[data-repeat-new]');
const $container = $template.parent();
$template.remove();
$container.append(
apidata.map(data =>{
const $snippet = $template.clone(true);
$snippet.find('[data-repeat-value-new]').each((i, el) => {
$(el).text(eval($(el).data('repeat-value-new')));
});
return $snippet;
})
);
});
Full example is here: https://codepen.io/anon/pen/JQWVGG?editors=0010 (the only change is in // Not Working
block).
What it does:
[data-repeat-new]
selector)[data-repeat-value-new]
selector)data-repeat-value-new
attribute, and we have data
variable in eval
's context, so, things just work)That eval
call might look dangerous, so:
data.property
or data.property[0]
)And a note re value of data-repeat-new
: you get your API data in your code, and you never assign it, so, I'm not sure how one could interpret value of that attribute. One way would be provide some repository of data, where there are arrays with their names, like this:
const repo = {
data1: [{id: 'rec1'}, {id: 'rec2'}, {id: 'rec3'}]
};
And then in your code you could do this:
const $template = $('[data-repeat-new]');
const $container = $template.parent();
$template.remove();
const data = repo[$template.data('repeat-new')];
$container.append(
data.map(data =>{
const $snippet = $template.clone(true);
$snippet.find('[data-repeat-value-new]').each((i, el) => {
$(el).text(eval($(el).data('repeat-value-new')));
});
return $snippet;
})
);