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

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

问题描述

我开发的应用程序需要我的用户这一形象甚至有负载的机会之前设置4条信息。此图片是中心式的应用程序,所以破碎图像链接使它看起来像整个事情是borked。我想有另一种形象取代其位置在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!

<一个href=\"http://docs.angularjs.org/api/ng.directive:ngSrc\">http://docs.angularjs.org/api/ng.directive:ngSrc

推荐答案

这是一个pretty简单的指令来监视错误加载图像和更换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天全站免登陆