AngularJS - How to use ng-if without HTML element

waqas picture waqas · Nov 1, 2013 · Viewed 37.8k times · Source

Is there a way to tell AngularJS not to display the top HTML element which has ng-if directive. I want angular to display child content only.

Angular Code:

    <div ng-if="checked" id="div1">
      <div id="div2">ABC</div>
      <div id="div3">KLM</div>
      <div id="div4">PQR</div>
   </div>

Rendered HTML:

   <div id="div1"> 
      <div id="div2">ABC</div>
      <div id="div3">KLM</div>
      <div id="div4">PQR</div>
   </div>

What I want:

   <div id="div2">ABC</div>
   <div id="div3">KLM</div>
   <div id="div4">PQR</div>

Here is a fiddle. http://jsfiddle.net/9mgTS/. I do not want #div1 in HTML. I just want #div2,3,4 if checked is true.

A possible solution can be adding ng-if to all child elements but I do not want to do this.

Answer

Mark Amery picture Mark Amery · Jun 28, 2015

There's a currently-undocumented pair of directives, ng-if-start and ng-if-end, that you can use for this. They behave analogously to the documented ng-repeat-start and ng-repeat-end directives, and you can see the unit tests for them if you like.

For example, given the following code:

<ul>
  <li ng-if-start="true">a</li>
  <li>b</li>
  <li>c</li>
  <li ng-if-end>d</li>
  <li ng-if-start="false">1</li>
  <li>2</li>
  <li>3</li>
  <li ng-if-end>4</li>
</ul>

the first four lis will be shown and the final four lis will be hidden.

Here's a live example on CodePen: http://codepen.io/anon/pen/PqEJYV

There are also ng-show-start and ng-show-end directives that work exactly the way you would expect them to.