空 ng-src 不更新图像 [英] empty ng-src doesn't update image

查看:28
本文介绍了空 ng-src 不更新图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 ng-src 指令是为了避免浏览器在 Angular 计算表达式之前请求图像.

I am using the ng-src directive in order to avoid the browser to request the image before Angular evaluate the expression.

ng-src={{image}} 将更新图像的 src 属性.我误解了为什么 ng-src 指令在表达式 ("myImage.png") 变为空 ("") 时不会更新图像的路径.

ng-src={{image}} will update the src attribute of the image if the expression "image" change. I misunderstand why the ng-src directive doesn't update the path of the image if the expression ("myImage.png") become empty ("").

当表达式变空时,ng-src 属性变空,但 src 属性仍然是最后一个已知的 src.所以它不会更新图像.为什么 src 属性没有更新(到一个空的 src),从而使图像消失".

When the expression become empty, the ng-src attribute become empty but the src attribute still the last known src. So it doesn't update the image. Why the src attribute isn't updated (to an empty src) so that the image "disappear".

这是一个 plunker

谢谢

推荐答案

这个问题的答案在 Angular 代码中.这不是错误,只是他们决定想要的行为.从 13895 行开始,你可以看到这个指令代码:

The answer to this is in the Angular code. It's not a bug, it's just the behavior they decided they wanted. Starting on line 13895, you can see this directive code:

forEach(['src', 'srcset', 'href'], function(attrName) {
   var normalized = directiveNormalize('ng-' + attrName);
   ngAttributeAliasDirectives[normalized] = function() {
   return {
      priority: 99, // it needs to run after the attributes are interpolated
      link: function(scope, element, attr) {
          attr.$observe(normalized, function(value) {

         if (!value)
             return;

         attr.$set(attrName, value);

         if (msie) element.prop(attrName, attr[attrName]);
       });
     }
    };
  };
});

关键在于:

if (!value) return;

如您所见,如果您将 ng-src 表达式更改为空字符串,这将永远不会更改实际的 src 值.你可以做一些 MadScone 建议的事情来解决这个问题.

So as you can see, if you change the ng-src expression to an empty string, this will never change the actual src value. You can get around this doing something MadScone suggested.

这篇关于空 ng-src 不更新图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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