【问题标题】:How to access src attribute within Angular directive when using ng-src使用 ng-src 时如何在 Angular 指令中访问 src 属性
【发布时间】:2015-01-05 22:39:27
【问题描述】:

我有以下 HTML(在 gsp 中):

<img ng-src="${resource(dir: '')}/images/stores/closeBTN.svg" />

我想使用 Modernizr 来检测是否支持 SVG,如果不支持,则将图像切换为 png。我已经修改了这个指令:https://github.com/tinacious/angular-svg-png

angular.module('svgPng', [])
  .directive('img', function () {
    return {
      restrict: 'E',
      link: function (scope, elem, attrs) {
        if ( typeof Modernizr !== 'undefined' && !Modernizr.svg ) {
          elem.attr('src', attrs.src.replace('.svg', '.png'));
        }
      }
    };
  });

问题是 attrs.src 未定义,因此替换不起作用。我知道 ng-src 应该填充 src,所以我需要强制一个摘要循环或其他东西来定义 src 吗?

【问题讨论】:

  • 语法${resource(dir: '')}是什么意思?
  • 这是一个 Grails 插件,可以正确生成指向静态资源的链接。只需在此处插入一条路径即可。

标签: html angularjs angularjs-directive


【解决方案1】:

在处理ng-src 并添加 src 属性的摘要周期之前,您这样做太早了。因此,让摘要循环发生,您可以通过将其放入 $timeout 或使用 setTimeout 来确保它。

 .directive('img', function () {
    return {
      restrict: 'E',
      link: function (scope, elem, attrs) {
        if ( typeof Modernizr !== 'undefined' && !Modernizr.svg ) {
         $timeout(function(){
            elem.attr('src', attrs.src.replace('.svg', '.png'));
         }, false);
        }
      }
    };
  });

或者更好的选择是不要在ngSrc 有机会处理它之前过早进行替换。使用 compile 函数替换 ng-src 属性值中的扩展名,这也可以防止加载两个图像,因为它会在前一种情况下发生(一个带有 .svg,一个带有 .png)。

 .directive('img', function () {
        return {
          restrict: 'E',
          compile: function (elem, attrs) {
            if ( typeof Modernizr !== 'undefined' && !Modernizr.svg ) {
               attrs.$set('ngSrc', attrs.ngSrc.replace('.svg', '.png'));
            }
          }
      };
 });

【讨论】:

  • 正是我想要的。非常感谢!
  • 虽然很少见,但您在 $timeout 中包装的代码不可能在摘要周期完成并添加 src attr 之前执行?
  • @user2943490 这种方法的另一个问题可能是重新替换,因为它发生得太晚了,图像将被下载并且还可能出现闪烁。所以我添加了另一种方法来在 ng-src 甚至可以处理它之前过早地执行替换。
  • @HellaMedusa 看看我的第二个选项
  • 谢谢,我会实现的。
猜你喜欢
  • 2019-11-23
  • 1970-01-01
  • 1970-01-01
  • 2014-11-08
  • 2015-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-15
相关资源
最近更新 更多