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?
有帮助吗?

解决方案

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

其他提示

I think the nesting mentioned by André Dion is a cleaner solution, but if you need this format you could use ng-if instead. This requires Angular 1.1.5+.

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

Docs: http://docs.angularjs.org/api/ng.directive:ngIf

Edit: While ng-show will simply hide the element, ng-if will remove it from the DOM entirely.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top