admin管理员组

文章数量:1180466

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>

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>
Share Improve this question edited Oct 6, 2021 at 4:12 Paul Rooney 21.6k9 gold badges44 silver badges62 bronze badges asked Jan 21, 2014 at 13:55 ClaCla 1,9184 gold badges22 silver badges37 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 27

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.

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>

本文标签: javascriptIs correct to use ngshow and nghide on the same DOM elementStack Overflow