我刚刚添加了一个CDN服务,使我的网站加载更快。对于使用<img>标记获取的照片,我有一个问题。
我有很多这样的案例:
// userProfile.thumbnailPhotoSrc = some/relative/path.png
ng-src="{{userProfile.thumbnailPhotoSrc}}"(我使用AngularJS)。
在启动时,我有一个脚本将CDN端点保存到window.cdn变量。如果脚本确定没有可用的端点::
window.cdn = '';所以我想要做这样的事情:
ng-src="window.cdn + {{userProfile.thumbnailPhotoSrc}"但这是不可能的,因为window.cdn没有被评估。但这两种方法都不起作用:
ng-src="{{window.cdn + userProfile.thumbnailPhotoSrc}"因为我只能在$scope下访问{{}}属性。我不能将CDN端点保存到$scope,因为每个控制器都有一个$scope (我有很多,这是不可维护的)。
我想到的最后一件事,希望ng-src允许-是添加一个在任何ng-src属性上运行的转换函数,但是我找不到如何做到这一点。
你建议我做什么?请记住,我希望网站从CDN中获取照片,并在CDN故障时返回到原始服务器(获取相对路径)。我怎么才能得到这种行为?
谢谢
发布于 2016-04-13 16:26:02
你可以用角创建一个自定义过滤器
然后,您将在模板中:
ng-src="{{userProfile.thumbnailPhotoSrc | cdn}"您可以将$window服务作为依赖项添加到筛选器服务中,这样就不必从全局对象中提取它,也可以测试过滤器。
发布于 2016-04-13 17:03:31
如果您试图更新所有<img>标记的src。您可以创建一个指令:
angular.module('imageCdnSrc', [])
.directive('img',['$interpolate', function($interpolate) {
return {
restrict: 'E',
scope: false,
compile: function(element, attrs) {
var ngSrc = attrs.ngSrc;
delete attrs.ngSrc; // prevent ngSrc directive to trigger
return function($scope,element,attrs) {
var ngSrcVal = $interpolate(ngSrc)($scope); //returns the string value of ngSrc
/* Add Logic Below to decide what to do */
if(window.cdn && ngSrcVal && ngSrcVal.length>0){
attrs.ngSrc = window.cdn + ngSrcVal;
/* if image fails to load with cdn, load the default */
element.one('error', function() {
angular.element(this).attr("src", ngSrcVal);
});
}
else{
attrs.ngSrc = ngSrcVal;
}
};
}
};
}]);https://stackoverflow.com/questions/36604282
复制相似问题