html - 使用 ng-src 时如何在 Angular 指令中访问 src 属性

标签 html angularjs angularjs-directive

我有以下 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?

最佳答案

你在摘要周期之前做得太早了,摘要周期处理 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 有机会处理它之前过早地进行替换。使用编译函数替换 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'));
            }
          }
      };
 });

关于html - 使用 ng-src 时如何在 Angular 指令中访问 src 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27789133/

相关文章:

javascript - 表单中自定义字段的指令 [范围未更新]

javascript - 类型错误 : Cannot read property 'bind' of undefined using ng-cropper directive

html - 使图像居中对齐

javascript - 语义 UI Accordion 重叠位置固定元素

angularJS valdr + ui-select 验证

javascript - 在 JSFiddle 中使用 Angular 创建 JSON 表

javascript - Angular JS Ng 重复问题

javascript - AngularJS:通过服务更新将指令绑定(bind)到 Controller

html - 在手机和平​​板电脑上隐藏页脚

html - IE中div定位问题