Matheus Medeiros
Matheus Medeiros

Reputation: 103

Why does ng-if messes up with my javascript while ng-show doesn't?

I have an element(a sidebar) where I only want to show it when the user is authenticated. This sidebar has some javascript actions, like expanding/contracting toggler. When I use ng-show, it works fine, but when I use ng-if it just stops working. Does anyone know why it happens? I don't have problem rendering it. The problem is some jquery scripts don't work while using ng-if. I know the difference between ng-if and ng-show, where ng-if creates a new DOM, scope and all, while ng-show just hides the element with CSS.

<div ng-if="sidebar && signedUser" ng-cloak>

    (some components here...)

    <ul class="navbar-nav sidenav-toggler">
      <li class="nav-item">
        <a class="nav-link text-center" id="sidenavToggler">
          <i class="fa fa-fw fa-angle-left"></i>
        </a>
      </li>
    </ul>
</div>

Expanded sidebar (using ng-if the toggler doesn't work)

Using ng-show I can contract it

Upvotes: 1

Views: 74

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222682

As others stated in the comment above,

ng-if will remove elements from DOM which means all your handlers or anything else attached to those elements will be lost.

ng-show/ng-hide does not remove the elements from DOM. It internally uses styles to hide/show elements

Upvotes: 3

Related Questions