【问题标题】:Get only one image of ng-repeat for a background image只获取一张 ng-repeat 的图像作为背景图像
【发布时间】:2015-03-03 07:20:19
【问题描述】:

试图只从 ng-repeat 中抓取一张图片作为 div 的背景图片。到目前为止有这个:

<div ng-repeat="photo in inventory.photos">
<div class="details-image" style="background-image: url({{photo}})">
            </div>
</div>

当然是显示所有照片。我将如何只获取该组的第一张图片?

【问题讨论】:

    标签: javascript angularjs indexing ng-repeat


    【解决方案1】:

    您可以尝试使用$first$middle$last。 例如:

    <div ng-repeat="photo in inventory.photos">
    <div class="details-image" style="background-image: url({{inventory.photos[$first]}})">
                </div>
    </div>
    

    链接here。查看$first$middle$last$index 的工作原理

    【讨论】:

    • 这是我即将给出的答案。你可能有理由仍然使用 ng-repeat。您还可以使用 ng-if 查看 $index === 0 是否切换整个 div。
    【解决方案2】:

    试试这个:

    <div ng-repeat="photo in inventory.photos">
        <div class="details-image" style="background-image: url({{inventory.photos[0]}})">
        </div>
    </div>
    

    我希望您不是为了获得第一张照片而循环浏览这些照片。如果你是,那么你甚至不需要 ng-repeat。

    <div>
        <div class="details-image" style="background-image: url({{inventory.photos[0]}})">
        </div>
    </div>
    

    【讨论】:

    • :) 我是,但你的第二个样本正是我需要的。仍然让我从 jQuery 中解脱出来,所以我可以通过简单地调用数组中对象的索引来获得我需要的东西这一事实仍然让我大吃一惊。
    【解决方案3】:

    不要使用 ng-repeat,只选择第一个

        <div class="details-image" ng-style="{'background-image': 'url('+ inventory.photos[0]+')'">
        </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 2014-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多