Search code examples
angularjsangular-ng-ifangularjs-ng-if

ng-if showing empty DOM element when condition is not true


I have the following in a view file:

  <p class="presentation black">Sections:
    <span data-ng-if="currentTab == 'tab1'">
      <div ng-repeat="question in filtered = (template.questions | unique:'sectionName')"></div>
      <p class="presentation black">{{filtered.length}}</p>
    </span>
    <span data-ng-if="currentTab == 'tab2'">
      <div ng-repeat="sheet in filtered = (template.sections[0].sheets | unique:'name')"></div>
      <p class="presentation black">{{filtered.length}}</p>
    </span>
  </p>

When tab1 is selected, the information is displayed correctly. However when on tab2, it appears that <p> element in both spans is being displayed - an empty value in displayed for the <p> element related to tab1. By looking at the DOM tree it also seems that when on tab2, the ng-if condition is not displaying: <!-- end ngIf: currentTab == 'tab2' -->. Can anyone see where the issue may be? Let me know if more code is required.


Solution

  • The "p" shouldn't be in a "span" according to HTML5 specs. Change the "span" to a "div".

    HTML

    <p class="presentation black">Sections:
       <div data-ng-if="currentTab == 'tab1'">
         <div ng-repeat="question in filtered = (template.questions | unique:'sectionName')"></div>
         <p class="presentation black">{{filtered.length}}</p>
       </div>
       <div data-ng-if="currentTab == 'tab2'">
         <div ng-repeat="sheet in filtered = (template.sections[0].sheets | unique:'name')"></div>
         <p class="presentation black">{{filtered.length}}</p>
       </div>
    </p>