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