user3814030
user3814030

Reputation: 1283

Conditional rendering on angularjs

I used to work with backbone and handlebars and was able to do things like

{{ if condition }}
  <div class="container">
{{ endif }}

  more html

{{ if condition }}
  </div>
{{ endif}}

I know I can use ng-if but I want to display conditionally an element opening and closing not the whole element.

Upvotes: 2

Views: 4849

Answers (2)

Vikas Garg
Vikas Garg

Reputation: 190

The simplest and best way to do this by using "ng-if" attribute for any HTML element that you want to render on the basis of some condition that you can manupulate in your controller as per your need.

For example:

<div ng-if = "expression">
</div>

This expression should be evaluate to be boolean i.e. either true or false, here you can specify multiple condition also which should be evaluate to true or false.

For multiple condition example check out this fiddle: http://jsfiddle.net/9Ymvt/820/

Check out this example in example section of "ngif doc":

https://docs.angularjs.org/api/ng/directive/ngIf

Upvotes: 0

Amir Popovich
Amir Popovich

Reputation: 29836

You can write a directive and accomplish exactly what you want, but I think a better way to do things is to create a div(without conditions - since every open div element has to have a closing element) and to add dynamic content inside using ng-if:

<div>
  <div ng-if="cond1"></div>
  <div ng-if="cond2"></div>
  <!-- ETC...... -->
</div>

Upvotes: 2

Related Questions