使用Angular JS ng-src的后备(默认)图像 [英] Fallback (default) image using Angular JS ng-src

查看:510
本文介绍了使用Angular JS ng-src的后备(默认)图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用从模态返回的数据来设置图像源。这是在ng-repeat循环中:

I'm trying to set an image source using data returned from a modal. This is inside an ng-repeat loop:

<div id="divNetworkGrid">
    <div id="{{network.id}}" ng-repeat="network in networks">
        <span>
            <table>
                <tr>
                    <td class="imgContainer">
                        <img ng-src="{{ ('assets/img/networkicons/'+ network.actual + '.png') || 
                                         'assets/img/networkicons/default.png' }}"/>
                    </td>
                </tr>
            </table>
        </span>
    </div>
</div>

很明显,我想在返回network.actual模型属性时填充default.png空值。但是我的代码没有拿起默认图像,虽然第一张图像在可用时会很好。

As is apparent, I want to populate default.png when the network.actual model property is returned as null. But my code is not picking up the default image, though the first image is coming up fine when available.

我确定这是一些语法问题,但是无法计算出了什么问题。

I'm sure this is some syntax issue, but cant figure out what's wrong.

推荐答案

有趣的使用方式 ng-src 。我还没有测试过如何处理这个表达式,但我建议这样做更稳定:

Interesting way to use ng-src. I haven't tested how that expression would be handled but I would suggest doing it a more stable way:

<img ng-src="{{ networkIcon }}" />

在您的控制器中:

$scope.networkIcon = network.actual ? 'assets/img/networkicons/' + network.actual + '.png' : 'assets/img/networkicons/default.png';

编辑:为了澄清,我不是建议最好的方法这样做是将图像源直接绑定到范围,而是将图像回退逻辑移到视图之外。在我的应用程序中,我经常在检索数据的服务中或在服务器本身上发送图像URL,因此客户端只需要担心单个属性。

Just to clarify, I'm not suggesting the best way to do this is to bind the image source directly to the scope but rather to move the image fallback logic outside of the view. In my applications I often do it in the services that retrieve the data or on the server itself and send an image URL so the client only has to worry about a single property.

编辑以处理转发器

angular.forEach($scope.networks, function(network) {
  network.icon = network.actual ? 'assets/img/networkicons/' + network.actual + '.png' : 'assets/img/networkicons/default.png';
});

<tr ng-repeat="network in networks">
  <td><img ng-src="{{ network.icon }}" /></td>
</tr>

这篇关于使用Angular JS ng-src的后备(默认)图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆