twitter-bootstrap 如果 angular 属性为空,则隐藏元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16225713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 16:59:03  来源:igfitidea点击:

Hide element if angular attribute is empty

htmltwitter-bootstrapangularjs

提问by zmanc

I have an image element that is getting its path from an attribute I have on my angular object. However if this (imagePath) is empty I get a broken image. I would like to not render the image if the attribute is empty however I do not see a way to do this. Any ideas?

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

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

回答by Tim B James

You want to check out ngHidedirective.

你想签出ngHide指令。

So your code would look something like.

所以你的代码看起来像。

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

Alternatively, you could also try the suggestion by darkporter

或者,您也可以尝试darkporter的建议

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

You could also update this to check if the object is null or undefined then hide the element.

您还可以更新它以检查对象是否为空或未定义,然后隐藏元素。

回答by Tj Gienger

This suggestion wouldn't work for me because I was generating my image links based on a users role. The user had a role, but that didn't mean they had an image associated with it.

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

So I created a directive:

所以我创建了一个指令:

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

So:

所以:

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

will not show if the .imagePath is empty or if there simply isn't an associated image.

如果 .imagePath 为空或者根本没有关联的图像,则不会显示。