2013-04-25 70 views
7

我有一个图像元素从我在角度对象上的属性获取其路径。但是,如果这个(imagePath)是空的,我得到一个破碎的图像。我想不显示图像,如果属性是空的,但我没有看到一种方法来做到这一点。有任何想法吗?如果角度属性为空,则隐藏元素

<img width="50px" src="/resources/img/products/{{current.manufacturerImage.imagePath}}"> 
+0

真正的即时通讯:http://stackoverflow.com/questions/14164371/inline-conditionals-in-angular-js/14165488#14165488 – bresleveloper 2013-08-08 21:51:30

回答

20

您想查看ngHide指令。

所以你的代码看起来像。

<img width="50px" ng-hide="current.manufacturerImage.imagePath == ''" 
src="/resources/img/products/{{current.manufacturerImage.imagePath}}"> 

或者,您也可以通过darkporter

<img width="50px" ng-show="current.manufacturerImage.imagePath" 
src="/resources/img/products/{{current.manufacturerImage.imagePath}}"> 

你也可以更新此检查的对象是null或undefined,则隐藏元素尝试的建议。

+9

非常确定ng-hide/show不需要适当的布尔值,并且可以使用真实性。我会做'ng-show =“current.manufacturerImage.imagePath”' – jpsimons 2013-04-26 05:36:19

+1

@darkporter,要小心这个方法的任何值都可以是0,但是像ID一样,因为这可能被错误地解析为虚假。 – adamdport 2014-05-14 18:57:23

0

这个建议对我不起作用,因为我是基于用户角色生成我的图像链接。用户有一个角色,但这并不意味着他们有一个与之相关的图像。

所以我创建了一个指令:

angular.module('hideEmptyImages', []) 
.directive('hideEmptyImage',function() { 
    return { 
     Restrict: 'AE', 
     Link: function (scope, elem, attrs) { 
      elem.error(function() { 
       elem.hide(); 
      }); 
     } 
    }; 
}); 

所以:

<img hide-empty-image width="50px" src="/resources/img/products/{{current.manufacturerImage.imagePath}}"> 

不会显示如果.imagePath为空,或者我们确实没有关联的图像。