Reaching angular ng-repeat as a function in javascript

Im currently working on code to achieve something like ng-repeat in angular. Mostly for-loop in html. the code takes each element with the class "loop" and processes it with the information specified through the attribute "info". Here is the code: HTML

<div class="loop" data-info="i in 1 to 10"> -i- </div> 

Javascript

 $(".loop").each(function(i){ var loop_info=$(this).attr("data-info"); var fin=loop_info.match(/(.*) in (\d+) to (\d+)/); var variable=fin[1], initial=fin[2], final=fin[3]; var htm=$(this).html(),printed=""; for(j=initial;j<=final;j++){ var temp=htm; var r=new RegExp("-("+variable+")-","g") temp=temp.replace(r,j); printed+=temp; } $(this).html(printed); }); 

Now I have also included a function to replace a variable with numbers.

Everything works fine, but when loops are nested in ie

 <div class="loop" data-info="i in 1 to 10"> <div class="loop" data-info="j in 1 to 10"> -j- </div> </div> 

it does not work in a nested loop, i.e. -j- is not replaced with numbers. I do not know why this is happening, any help is appreciated.

+5
source share
1 answer

The replacement fails due to an HTML change, and the next .loop link that jQuery has compiled for your for loop no longer represents what it was before.

Instead, loop the for loop in the opposite direction:

 $($(".loop").get().reverse()).each(function(i){ // etc... 

Excerpt:

 $($(".loop").get().reverse()).each(function(i){ var loop_info=$(this).attr("info"); var fin=loop_info.match(/(.*) in (\d+) to (\d+)/); var variable=fin[1], initial=fin[2], final=fin[3]; var htm=$(this).html(),printed=""; for(j=initial;j<=final;j++){ var temp=htm; var r=new RegExp("-("+variable+")-","g") temp=temp.replace(r,j); printed+=temp; } $(this).html(printed); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="loop" info="i in 1 to 10"> <div class="loop" info="j in 1 to 10"> -i-:-j- </div> </div> 
+7
source

All Articles