angularjs - 如果加载的 ng 样式图像无效 url,则背景默认图像

标签 angularjs angularjs-scope angularjs-ng-repeat angular-ui

我正在像这样向我的 div 添加背景图像

ng-style="{'background-image' : 'url('+ myvariable.for.image +')'}">

其中 myvariable.for.image 是像/examplesite/image/id 这样的 url

这可以正常工作,但有一个异常(exception),如果图像不存在,它就不会做任何事情,而且我的背景看起来太白了......如果图像不存在,我希望能够用默认图像替换它。

但我似乎无法弄清楚如何

最佳答案

而不是 ngStyle我会为此使用自定义指令。比如下面的。这会检查是否提供了属性,如果是,则尝试加载该图像。如果它加载了图像,那么我们将背景图像设置为它,否则我们使用默认图像。

myApp.directive('bgImage', function () {
    return {
        link: function(scope, element, attr) {

            attr.$observe('bgImage', function() {           
              if (!attr.bgImage) {
                 // No attribute specified, so use default
                 element.css("background-image","url("+scope.defaultImage+")");
              } else {
                 var image = new Image();  
                 image.src = attr.bgImage;
                 image.onload = function() { 
                    //Image loaded- set the background image to it
                    element.css("background-image","url("+attr.bgImage+")");
                 };
                 image.onerror = function() {
                    //Image failed to load- use default
                    element.css("background-image","url("+scope.defaultImage+")");
                 };
             }
         });
      }
    };
});

像这样使用:
 <div bg-image="{{person.src}}">

demo fiddle

关于angularjs - 如果加载的 ng 样式图像无效 url,则背景默认图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21056699/

相关文章:

javascript - 对话框不关闭

javascript - 在 AngularJS ng 类中链接多个表达式

angularjs - Nodejs : Using i18n-2 Client side or Server side or both

javascript - ion-content 和 ion-footer 有不同的 $scope

javascript - 当项目不可见时在 ng-bind 中注销观察者

javascript - 变量更改后 Angular.js 更新范围

javascript - 使 url 匹配 '/' 、 '/index' 和 '/index.html' 到单个状态

javascript - 隔离仅限于属性的指令的范围

javascript - 带有数据属性的 Angular 'ng-repeat' 函数的纯 javascript/jquery 解决方案?

angularjs - 在angularjs中的一定数量的字符后面放置省略号(...)