javascript 在同一个 DOM 元素上使用 ng-show 和 ng-hide 是否正确?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21260161/
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-27 20:29:33  来源:igfitidea点击:

Is correct to use ng-show and ng-hide on the same DOM element?

javascriptangularjs

提问by jollyr0ger

I was wondering if is a good practice to use ng-show and ng-hide on the same DOM element.

我想知道在同一个 DOM 元素上使用 ng-show 和 ng-hide 是否是一个好习惯。

It seems a better idea, instead of using multiple conditions, some of which negated, in a single ng-show.

这似乎是一个更好的主意,而不是在单个 ng-show 中使用多个条件,其中一些条件被否定。

Let me know. Thanks!

让我知道。谢谢!

PS: here an example

PS:这里有一个例子

<div ng-show="isBlonde" ng-hide="hasBlueEye">Mary is blonde and she has green eyes</div>

<div ng-show="isBlonde" ng-hide="hasBlueEye">Mary is blonde and she has green eyes</div>

回答by André Snede Kock

Absolutely not.

绝对不。

First of all, the two directives can trip over each other( see this JSFiddle, as provided by Joel Skrepnek), and is generally just bad design.

首先,这两个指令可以相互绊倒(请参阅此JSFiddle,由Joel Skrepnek提供),并且通常只是糟糕的设计。

You can use a function, another field or just some more inline-logic.

您可以使用一个函数、另一个字段或更多的内联逻辑。

Inline-Logic:

内联逻辑:

<div ng-show="isBlonde && !hasBlueEye">Mary is blonde and she has green eyes</div>

Field:

场地:

<div ng-show="shouldShowThisDiv">Mary is blonde and she has green eyes</div>

Function

功能

<div ng-show="shouldShowThisDiv()">Mary is blonde and she has green eyes</div>

$scope.shouldShowThisDiv = function(){
    return $scope.isBlonde && !$scope.hasBlueEye;
}

My recommendationwould be to use either another fieldor a function, if there are more than 2 values that needs to be checked.

如果需要检查的值超过 2 个,我的建议是使用另一个字段函数

回答by Gruff Bunny

Use one but not both. Choose the one which makes the expression the most readable.

使用一个,但不要同时使用。选择使表达式最易读的一种。

Otherwise you could end up with:

否则你可能会得到:

<div ng-show='true' ng-hide='true'></div>