What's the difference between `ng-show` and `ng-hide`?

后端 未结 5 1445
天命终不由人
天命终不由人 2020-12-11 18:08

These attributes are both given either a true or false value, so what difference is there between them? It would make sense if there weren\'t value

相关标签:
5条回答
  • 2020-12-11 18:26

    With ng-show the element is shown if the expression is true, it will hide if it is false

    On the other hand with ng-hide the element is hidden if the expression is true and it will be shown if it is false.

    Just two sides of the same coin.

    0 讨论(0)
  • 2020-12-11 18:26

    i have a good scenario, let say you want to show one attribute or another depending on a validation, but not both, so using both ng-show and ng-hide like this:

    <div ng-show="validation"></div>
    <div ng-hide="validation"></div>
    

    if the validation is true it would show the first div, but if it is false it would show the second div... this can be done in many more ways but is a cleaver solution for a tricky problem :D

    0 讨论(0)
  • 2020-12-11 18:26

    ng-show will only display the element IF the expression is true...

    <span ng-show="true">Will Show </span>
    <span ng-show="false">Will not Show </span>
    

    ng-hide will not display the element IF the expression is true, but will display if the expression is false.

    <span ng-hide="true">Will not display</span>
    <span ng-hide="false">Will display</span>
    
    0 讨论(0)
  • 2020-12-11 18:27

    Also worth mentioning is ng-if which takes a boolean expression just like ng-show and ng-hide but rather than just showing/hiding the elements depending on the expression, it completely removed the element from the DOM if the expression is false and put the element back in the DOM if the expression becomes true

    0 讨论(0)
  • 2020-12-11 18:49

    On a project I was working on before, I found having the option of both ng-show and ng-hide useful. The reason being is because I had a link in my navbar that was only supposed to show if the user was on a specific view. Here is that scenario:

    <li ng-hide="isActive('/about') || isActive('/contact')" ng-class="{ 'vert-nav-active': isActive('/investigator')}" class="top-buffer">
    <a href="#/investigator" class="buff-sides navListLinks">Investigator Portal</a>
    </li>
    

    Now, you might say, well you could just make the isActive('/about') || isActive('/contact') return the opposite Boolean and change the ng-hide to ng-show and every thing will stay the same but as you can see I'm also using this function to determine which link I'm on. If I reverse this logic, it will look like I'm on every link except the actual link I'm on. Granted I could write another function for the ng-show but I like reusing code that's already there.

    0 讨论(0)
提交回复
热议问题