AngularJS 'ng-switch-when' with an expression

1.7k Views Asked by At

I know ng-switch-when expects a value, but I created a ng-repeat with it.

What do I need to make for this to work?:

<div ng-switch-when="2" ng-controller="pages as page" ng-switch="page.get()">
    <div ng-repeat="i in [1,2,3,4,5]">
        <div ng-switch-when="{{ i }}">
            {{i}}
        </div>
    </div>
    <button ng-hide="page.is(1)" ng-click="page.prev()" class="btn btn-info">Previous Page</button>
    <button ng-hide="page.is(5)" ng-click="page.next()" class="btn btn-info">Next Page</button>
    <br>
    <label>Page {{page.get()}}</label>
</div>

I want to show the div when the value is "i", but angularjs doesn't accept that.

I don't know if that makes much difference, but I'm using a ng-switch inside a div which is being displayed by another ng-switch.

Thanks in advance

EDIT 1: I want to create with a ng-repeat 5 pages, which are inside a ng-switch. When the repeat "i" value is one, I want the page it created to be displayed when the switch value equals one, also, and that for the rest of them

2

There are 2 best solutions below

1
Ahsan On

Try something like this:

<div ng-controller="pages as page" ng-switch="page.get()">
    <div ng-repeat="i in [1,2,3,4,5]">
      <div ng-switch = "i">
        <div ng-switch-when = "1">
          1
        </div>
        <div ng-switch-when = "2">
          2
        </div>
        <div ng-switch-when = "3">
          3
        </div>
        <div ng-switch-when = "4">
          4
        </div>
        <div ng-switch-when = "5">
          5
        </div>
      </div>
    </div>
    <button ng-hide="page.is(1)" ng-click="page.prev()" class="btn btn-info">Previous Page</button>
    <button ng-hide="page.is(5)" ng-click="page.next()" class="btn btn-info">Next Page</button>
    <br>
    <label>Page {{page.get()}}</label>
</div>
0
Tex Andersen On

Simply put:

You can't.

From the docs:

Be aware that the attribute values to match against cannot be expressions. They are interpreted as literal string values to match against.

What you could do to achieve the same result is use ng-show as follows:

<div ng-repeat="i in [1,2,3,4,5]">
    <div ng-show="page.get() === i">
        {{i}}
    </div>
</div>