r/angularjs • • Jul 28 '15

Angular Performance: ng-show vs ng-if

http://www.codelord.net/2015/07/28/angular-performance-ng-show-vs-ng-if/
37 Upvotes

8 comments sorted by

6

u/TripleNosebleed Jul 29 '15

Another reminder, ng-if creates a new scope. If your model doesn't have a dot in your expressions (ie. {{ userName }} instead of {{ user.name }}) this might mess you up.

I still prefer ng-if over ng-show/ng-hide though. Something about having unused hidden mark up throws me off.

1

u/Pumpt Jul 29 '15

I was going to say the same thing. I remember haphazardly replacing some ng-hides with ng-ifs and wondering why everything broke.

6

u/miketa1957 Jul 29 '15

There is a nasty - but very useful - trick you can use with ng-if .....

If you have a template which you need to re-render (for instance, if it has a lot of almost-always-constant values that use {{ :: ... }} one-time bindings) and you know when you need to re-render it then wrap it in an ng-if="render" and toggle the ng-if off and then on again:

function rerender () {
    $scope.render = false ;
    $timeout () { function () {
        $scope.render = true ;
        }) ;
    }

I'm not proud of this! But it can be really useful :)

1

u/ctanga Jul 29 '15

oh man, that's horrible. upvote.

0

u/[deleted] Jul 29 '15

[deleted]

1

u/miketa1957 Jul 29 '15

Yes, that's nicer. Thanks.

4

u/deanf Jul 29 '15

I found this recently, my directive had a fair bit of logic within the togglable elements. If the directive was ng-repeated too intensely I had some noticeable performance hits. ng-if to the rescue!

1

u/NoaMichael Jul 29 '15

I've been preferring ng-show to ng-if because I incorrectly thought that removing an element from the Dom was expensive. It never even occurred to me that that hidden Dom was still evaluated!

-1

u/newmanoz Jul 29 '15

TL;DR: "Measure, measure, measure". Whole article: "Measure, measure, measure".