如果 ngSrc 路径解析为 404,有没有办法回退到默认值? [英] if a ngSrc path resolves to a 404, is there a way to fallback to a default?

查看:18
本文介绍了如果 ngSrc 路径解析为 404,有没有办法回退到默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建的应用程序要求我的用户在该图像有机会加载之前设置 4 条信息.该图像是应用程序的核心部分,因此断开的图像链接使它看起来整个事情都被破坏了.我想在 404 上使用另一个图像.

The application I'm building requires my user to set 4 pieces of information before this image even has a chance of loading. This image is the center-piece of the application, so the broken image link makes it look like the whole thing is borked. I'd like to have another image take its place on a 404.

有什么想法吗?我想避免为此编写自定义指令.

Any ideas? I'd like to avoid writing a custom directive for this.

我很惊讶找不到类似的问题,尤其是当文档中的第一个问题是相同的时!

I was surprised that I couldn't find a similar question, especially when the first question in the docs is the same one!

http://docs.angularjs.org/api/ng.directive:ngSrc

推荐答案

这是一个非常简单的指令,用于观察加载图像的错误并替换 src.(Plunker)

It's a pretty simple directive to watch for an error loading an image and to replace the src. (Plunker)

HTML:

<img ng-src="smiley.png" err-src="http://google.com/favicon.ico" />

Javascript:

Javascript:

var app = angular.module("MyApp", []);

app.directive('errSrc', function() {
  return {
    link: function(scope, element, attrs) {
      element.bind('error', function() {
        if (attrs.src != attrs.errSrc) {
          attrs.$set('src', attrs.errSrc);
        }
      });
    }
  }
});

如果你想在 ngSrc 为空时显示错误图像,你可以添加这个 (Plunker):

If you want to display the error image when ngSrc is blank you can add this (Plunker):

attrs.$observe('ngSrc', function(value) {
  if (!value && attrs.errSrc) {
    attrs.$set('src', attrs.errSrc);
  }
});

问题是如果值为空,ngSrc 不会更新 src 属性.

The problem is that ngSrc doesn't update the src attribute if the value is blank.

这篇关于如果 ngSrc 路径解析为 404,有没有办法回退到默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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