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

All we need is an easy explanation of the problem, so here it is.

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

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

Let me know.
Thanks!

PS: here an example

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

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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.

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 recommendation would be to use either another field or a function, if there are more than 2 values that needs to be checked.

Method 2

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>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply