Alternating ng-repeat results between others

时间:2017-04-10 00:03:39

标签: angularjs angularjs-ng-repeat

I have a blog which content completes through an AngularJS controller that bring data from DB.

On the other hand, an object conformed by the image files sited in a especific directory

Now, with these two objects I want implement a ng-repeat that shows 2 images every 4 posts like this:

<div>post 1</div>
<div>post 2</div>
<div>post 3</div>
<div>post 4</div>
<div>image 1</div>
<div>image 2</div>
<div>post 5</div>
<div>post 6</div>
<div>post 7</div>
<div>post 8</div>
<div>image 3</div>
<div>image 4</div>
<div>post 9</div>
<div>...

The issue is in images repeat. Instead continues with image 3 and 4 after first repeat the controller shows image 1 and 2 again and again.

The current code I have is something like this:

<div ng-controller="noticias">
  <div ng-repeat-start="noticia in noticias">
    <h1>{{ noticia.titulo }}</h1>
    <p>{{ noticia.asunto }}</p>
  </div>
  <div ng-repeat-end ng-if="($index+1) % 4 ===0">
    <div ng-repeat="anuncio in anuncios | limitTo: 2>
      <img ng-src="anuncios/{{ anuncio.nombre }}
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

Instead of starting ng-repeat again, you need to keep track of index of the last image rendered and then use it as index. Something like following code should work, where imageIndex is an integer property in your controller and on initialization you set it to 0. I have not tested it though with some tweaks this should work:

<div ng-controller="noticias">
 <div ng-repeat-start="noticia in noticias">
 <h1>{{ noticia.titulo }}</h1>
 <p>{{ noticia.asunto }}</p>
</div>
<div ng-repeat-end ng-if="($index+1) % 4 ===0">
 <div>
   <img ng-src="anuncios/{{ anuncios[ctrl.imageIndex].nombre }}"/>
   <img ng-src="anuncios/{{ anuncios[ctrl.imageIndex+1].nombre }}"/>
    {ctrl.imageIndex = ctrl.imageIndex+1}
 </div>
</div>