Cla
Cla

Reputation: 1938

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>

Upvotes: 16

Views: 14875

Answers (2)

Gruff Bunny
Gruff Bunny

Reputation: 27976

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>

Upvotes: 6

Andr&#233; Snede
Andr&#233; Snede

Reputation: 10045

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.

Upvotes: 27

Related Questions