Search code examples
angularjsangular-ng-ifangularjs-ng-show

When to use ng-if vs ng-show/ng-hide?


I understand that ng-show and ng-hide affect the class set on an element and that ng-if controls whether an element is rendered as part of the DOM

Are there any examples on choosing ng-if over ng-show/ng-hide or vice-versa?


Solution

  • You've already summed it up in your question. If you want to show and hide the DOM depending on a condition, use ng-show. This works well for DOM transitions between workflows, tabs, sections, etc.

    <div ng-show="vm.tab == 'products'"></div>
    

    If you only want to conditionally render the DOM if a condition occurs, use ng-if. This is particularly useful for permissions where you aren't interested in exposing any more DOM than necessary.

    <button ng-if="vm.data.allowSubmit" ng-click="vm.submit()" />