1

The code I am working on has this:

<div ng-if="cos.connectMessage" style="text-align: center;" class="ng-scope">
    Unable to establish a connection to the localhost server for 5 minutes.</div>

Is there any advantage to using ng-show or ng-if to control the visibility of this message?

Alan2
  • 23,493
  • 79
  • 256
  • 450
  • yes, if the `connectMessage` value changes in the model it will automatically update the view and vice versa – Anonymous Duck Mar 23 '16 at 05:13
  • @Katana - but isn't that the same with ng-if and ng-show? – Alan2 Mar 23 '16 at 05:16
  • definitely yes, the only difference is the purpose and usage of that directive but the two-way data binding concept is still there – Anonymous Duck Mar 23 '16 at 05:18
  • Possible duplicate of [When to favor ng-if vs. ng-show/ng-hide?](http://stackoverflow.com/questions/21869283/when-to-favor-ng-if-vs-ng-show-ng-hide) – georgeawg Mar 23 '16 at 07:46

3 Answers3

2

ng-show

The ngShow directive shows or hides the given HTML element based on the expression provided to the ngShow attribute. The element is shown or hidden by removing or adding the .ng-hide CSS class onto the element. (reference)

ng-if

The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM. (reference)

Note: When ng-if removes the element it also removes the associated scope for that element and it get recreated when condition turns true.

Advantage

I prefer the use of ng-if specifically when number of watchers bound inside the element is more as it would completely destroy the scope so making the UI a bit faster. But for small elements or elements containing less watchers does cost overhead of removing scope and recreating it.

Jenish Rabadiya
  • 6,708
  • 6
  • 33
  • 62
  • 1
    you just copied and pasted :-( What I would like to know is if there is any advantage between using one or the other for the purpose i'm using. thanks – Alan2 Mar 23 '16 at 05:15
0

You can refer this for your solution, already lot of things asked in that what is the difference between ng-if and ng-show/ng-hide

Community
  • 1
  • 1
0

If you are using ng-if="false" then html content under ng-if will not includ in your html page, but if you are using ng-hide="true" or ng-show="false" then html part includ in your html page but it will only in hidden mode.

Vinit Solanki
  • 1,863
  • 2
  • 15
  • 29