Search code examples
javascripthtmldynamicrivets.js

How to construct Dynamic HTML using rv-each


I have two arrays truck and jobs. Now i have to construct a list using those two arrays. It will be like looping two for loops. For each element(id) in the first array(truck) I need to loop through the second array(jobs) with the respective job id alone.

for example : id:1 - should contain - thing1,thing2,thing3,thing4 id:2 - should contain - thing5,thing6,thing7,thing8

i need to construct a dynamic html for the above list using rv-each or rivets.

here is my fiddle : http://jsfiddle.net/keshav_1007/wa5osfec/3/

HTML :

<div id="contentWrap">
    <ol rv-each="truck" rv-value="truck.id">
        <li rv-each-job="jobs" rv-value="job.id">{ job.job_number }</li>
    </ol>
</div>

JS :

    $(document).ready(function(){
    window.view = rivets.bind($('#contentWrap'),{
        truck:[{id:1},
               {id:2},
               {id:3},
               ],
        jobs:[
            {id:1,job_number:'thing1'},
            {id:1,job_number:'thing2'},
            {id:1,job_number:'thing3'},
            {id:1,job_number:'thing4'},
            {id:2,job_number:'thing5'},
            {id:2,job_number:'thing6'},
            {id:2,job_number:'thing7'},
            {id:2,job_number:'thing8'},
        ]
    });
});

Now i am getting all the items in the array. But i need to get only the elements with respect to the first array as i mentioned in "for example".

help me on this. I tried and i couldnt make it work.

thanks in advance.


Solution

  • Take a look at this: http://rivetsjs.com/docs/guide/#formatters

    I've created (updated) your fiddle: http://jsfiddle.net/wa5osfec/7/

    HTML:

    use the formatter to modify the returned value to rv-each-*. of course you can pass also your value (in this case your id) which you want to compare.

    <li rv-each-job="jobs | compare truck.id" rv-value="job.id">{ job.job_number }</li>
    

    JS:

    (be carefull. the forEach is not really well thought out. consider that it will not be performant on bigger arrays and repeats)

    rivets.formatters.compare = function(array, compare) {
    
        var tempArr = [];
    
        array.forEach(function(element, index, array) {
            if (element.id == compare) {
                tempArr.push(element);
            }
        });
    
        console.log(tempArr);
    
        return tempArr;
    }