Search code examples
javascriptangularjsng-switch

Is it possible to place the ng-switch-when attribute on multiple elements?


I'm trying to switch elements using ng-switch showing specific elements when I set a certain index.

ng-switch is working, except it's only showing the last switch statement.

I'm only showing the "Frame 2" div when using this code:

<div ng-switch="frame">
  <div ng-switch-when="1">Frame 1</div>
  <span>Some permanent text</span>
  <span ng-switch-when="2">Text relevant to frame 2</span>
  <div ng-switch-when="2">Frame 2</div>
</div>

I want the above to show all switch-when when frame is set to 2.

Note: The markup can't change.

  • How can I do this?
  • And if I can't is there a better/different alternative?

Solution

  • Nest your markup:

    <div ng-switch="frame">
        <div ng-switch-when="1">Frame 1</div>
        <span>Some permanent text</span>
        <div ng-switch-when="2">
            <span>Text relevant to frame 2</span>
            <div>Frame 2</div>
        </div>
    </div>
    

    Edit: OP edited his question to specify that the markup cannot change.

    You can't apply the same ng-switch-when to multiple elements. You can use ng-show though:

    <div>
        <div ng-show="frame == 1">Frame 1</div>
        <span>Some permanent text</span>
        <span ng-show="frame == 2">Text relevant to frame 2</span>
        <div ng-show="frame == 2">Frame 2</div>
    </div>
    

    DEMO