Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - How to use ng-if without HTML element

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.

like image 385
waqas Avatar asked Nov 01 '13 05:11

waqas


People also ask

What can I use instead of ngIf?

So if you can have choice between ngIf and hidden, prefer hidden.

Does ngIf work on Div?

The Angular ngIf directive works essentially as an if statement for HTML, adding this missing feature to the language under the form of the special ngIf attribute. In this example, the container div will only be shown to the user if the user is logged in, otherwise the whole content of the div is not visible.

Does ngIf remove element from DOM?

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.


1 Answers

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.

like image 122
Mark Amery Avatar answered Sep 19 '22 08:09

Mark Amery