Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 216
Cla Avatar asked Jan 21 '14 13:01

Cla


People also ask

Can we use ng-show and Ng-hide together?

For example if we want to hide a div based on a condition then we need to pass a boolean expression to ng-hide directive. ng-show/ng-hide can show and hide the rendered data, that is, it always kept the rendered data and show or hide on the basis of that directives.

What is the difference between ng-show ng-hide and Ng-if directives?

Basic Difference between ng-if, ng-show and ng-hideThe ng-hide directive shows or hides the given HTML element based on the expression provided to the ng-hide attribute . ng-if can only render data whenever the condition is true. It doesn't have any rendered data until the condition is true.

What is the difference between ngIf and hidden?

ngIf will comment out the data if the expression is false. This way the data are not even loaded, causing HTML to load faster. [hidden] will load the data and mark them with the hidden HTML attribute. This way data are loaded even if they are not visible.

Why do we use ng-show?

The ng-show Directive in AngluarJS is used to show or hide the specified HTML element. If the given expression in the ng-show attribute is true then the HTML element will display otherwise it hides the HTML element. It is supported by all HTML elements.


2 Answers

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.

like image 164
André Snede Avatar answered Oct 11 '22 12:10

André Snede


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>
like image 34
Gruff Bunny Avatar answered Oct 11 '22 13:10

Gruff Bunny