Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs templates: How to conditionally wrap a tag in another tag

Tags:

angularjs

ngIf conditionally adds/removes a tag to the DOM.

But if I want to conditionally wrap one tag (eg content) in another (eg layout) what is the most angular way to do this?

Below is how I would do it in Handlebars

{{#if layout}} <div class="layout"> {{/if}}
    Content is always here, it is wrapped only if layout is specified
{{#if layout}} </div> {{/if}}
like image 514
Ashley Coolman Avatar asked Oct 01 '22 17:10

Ashley Coolman


1 Answers

I may not fully understand your end goal here, but it seems like it'd be invalid html .

Regardless, your best options would be to write a directive that builds your html for you.

If you're not comfortable with custom directives, then the easier implement would be ngSwitch. It would let you set one way as the default, then you'll switch to the other one based on the expression that determines whether layout is to be wrapped or not.

Only thing I don't like about using ngSwitch in this type of case, it requires duplicating a bit of code. In this case it's very minimal.

If you have to do this throughout your application a few times, it'd be worth writing your own directive to do it in my opinion.

like image 132
EnigmaRM Avatar answered Oct 29 '22 21:10

EnigmaRM