【问题标题】:Hide element if angular attribute is empty如果角度属性为空,则隐藏元素
【发布时间】:2013-04-19 23:52:24
【问题描述】:

我有一个图像元素,它从我的角度对象上的属性获取其路径。但是,如果这个 (imagePath) 是空的,我会得到一个损坏的图像。如果属性为空,我不想渲染图像,但是我看不到这样做的方法。有什么想法吗?

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

【问题讨论】:

标签: html twitter-bootstrap angularjs


【解决方案1】:

您想查看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 或未定义,然后隐藏元素。

【讨论】:

  • 相当肯定 ng-hide/show 不需要适当的布尔值并且可以使用真实性。我会做ng-show="current.manufacturerImage.imagePath"
  • @darkporter,对于任何可以为 0 的值(例如 ID),请谨慎使用这种方法,因为这可能会被错误地解析为 falsy。
【解决方案2】:

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

所以我创建了一个指令:

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 为空或根本没有关联图像,则不会显示。

【讨论】:

    【解决方案3】:

    也可以使用 ngIf 指令,如下所示:

    <img width="50px" *ngIf="current.manufacturerImage.imagePath !== ''" 
    src="/resources/img/products/{{current.manufacturerImage.imagePath}}">
    

    【讨论】:

    • 这是正确的答案。感谢您保持更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 2017-08-24
    • 1970-01-01
    • 2016-10-06
    • 2016-08-09
    • 2022-01-16
    相关资源
    最近更新 更多