在数组中的每个x元素中插入新行

时间:2014-08-26 20:58:22

标签: javascript angularjs

我有这样的标记:

<div class="row">
    <div class="col col-50" ng-repeat="picture in pictures.slice().reverse()">
        <a href="instagram://media?id={{picture.id}}" title="{{picture.caption.text}}" target="_blank">
            <img ng-src="{{picture.images.standard_resolution.url}}" width="100%" height="auto" alt="{{picture.caption.text}}" />
        </a>
    </div>
</div>

我正在尝试创建一个均匀的布局,每行有两个图像。问题是,我需要每两年添加一行,因此我的ng-repeat无效。例如,标记一旦呈现就应该看起来像这样:

<div class="row">
    <div class="col col-50">
        <a href="instagram://media?id=213" title="Blah blah" target="_blank">
            <img ng-src="something" width="100%" height="auto" alt="Blah blah" />
        </a>
    </div>
    <div class="col col-50">
        <a href="instagram://media?id=213" title="Blah blah" target="_blank">
            <img ng-src="something" width="100%" height="auto" alt="Blah blah" />
        </a>
    </div>
</div>
<div class="row">
    <div class="col col-50">
        <a href="instagram://media?id=213" title="Blah blah" target="_blank">
            <img ng-src="something" width="100%" height="auto" alt="Blah blah" />
        </a>
    </div>
    <div class="col col-50">
        <a href="instagram://media?id=213" title="Blah blah" target="_blank">
            <img ng-src="something" width="100%" height="auto" alt="Blah blah" />
        </a>
    </div>
</div>

没有用Javascript手动输出,我真的不知道该怎么做。我一直在看文档,但我找不到办法。有人可以建议一些事情,还是指出我正确的方向?

1 个答案:

答案 0 :(得分:0)

只要图片阵列的长度很长,使用ng-switch就可以正常工作。

<div class="row" ng-repeat="picture in pictures.slice().reverse()" ng-switch on="$index % 2"  ng-show="$index%2==1">
  <div class="col col-50" ng-switch-when="1">
      <a href="instagram://media?id={{pictures[$index-1].id}}" title="{{pictures[$index-1].caption.text}}" target="_blank">
        <img ng-src="{{pictures[$index-1].images.standard_resolution.url}}" width="100%" height="auto" alt="{{pictures[$index-1].caption.text}}" />
    </a>
  </div>
  <div class="col col-50" ng-switch-when="1">
      <a href="instagram://media?id={{picture.id}}" title="{{picture.caption.text}}" target="_blank">
        <img ng-src="{{picture.images.standard_resolution.url}}" width="100%" height="auto" alt="{{picture.caption.text}}" />
    </a>
  </div>
</div>

在Fiddle中如何工作的简单示例: http://jsfiddle.net/HB7LU/5711/