-1

I was going through ng-if , ng-show and ng-hide but not completely gain it, all three of them doing the same thing so why there is three directive for one purpose?

peepaa
  • 1
  • 4

2 Answers2

1

The Differences

Both ng-show and ng-if receive a condition and hide from view the directive’s element in case the condition evaluates to false. The mechanics they use to hide the view, though, are different.

ng-show (and its sibling ng-hide) toggle the appearance of the element by adding the CSS display: none style.

ng-if, on the other hand, actually removes the element from the DOM when the condition is false and only adds the element back once the condition turns true.

Since ng-show leaves the elements alive in the DOM, it means that all of their watch expressions and performance cost are still there even though the user doesn’t see the view at all. In cases where you have a few big views that are toggled with ng-show you might be noticing that things are a bit laggy (like clicking on buttons or typing inside input fields).

If you just replace that ng-show with an ng-if you might witness considerable improvements in the responsiveness of your app because those extra watches are no longer happening.

That’s it: replace ng-show and ng-hide with ng-if!

Aman
  • 806
  • 2
  • 12
  • 38
  • Might want to add that `ng-if` creates its **own scope**. That means `ng-model="something"` will not work inside it. It will need to reach its parent's scope with `ng-model="$parent.something"` – Aleksey Solovey Jan 08 '18 at 10:11
0

The difference between ng-if and ng-show/ng-hide is that ng-if would not insert html fragment into the DOM if the condition results in false while ng-show/ng-hide would always insert html into the DOM but make it either visible or invisible.

Kabachok
  • 573
  • 1
  • 7
  • 22