1

I am trying to make a simple switch when statement in my Angular template and the switch statement output must be "You're a user" but it says that I am a guest.

What is wrong with my code?

<p><strong>Current role</strong></p>
<p>{{ app.currentUser.role }}</p>
<p><strong>Role to compare with</strong></p>
<p>{{ app.userRoles.user }}</p>

output:

Current role
user

Role to compare with
user

Switch statement

<div ng-switch on="app.currentUser.role">
  <div ng-switch-when="app.userRoles.admin">You're admin.</div>
  <div ng-switch-when="app.userRoles.moderator">You're moderator.</div>
  <div ng-switch-when="app.userRoles.user">You're a user.</div>
  <div ng-switch-default>You're a guest.</div>
</div>

output:

You're a guest.

Angular controller:

function MainController() {
    my = this;

    my.currentUser = { role : 'user'};
    my.userRoles = { user : 'user' };

  }

Plunker link: https://plnkr.co/edit/oCKVTjfTwkwYO9UVQU6X?p=preview

3 Answers 3

2

According to the docs for ngSwitch:

Be aware that the attribute values to match against cannot be expressions. They are interpreted as literal string values to match against. For example, ng-switch-when="someVal" will match against the string "someVal" not against the value of the expression $scope.someVal.

It looks like you won't be able to match against app.userRoles.** as you currently are. If you use something like:

<div ng-switch-when="user">You're a user.</div>

You should get the desired result.

Source: https://docs.angularjs.org/api/ng/directive/ngSwitch

Sign up to request clarification or add additional context in comments.

Comments

2

Your template should be like the below,

<div ng-switch on="app.currentUser.role">
  <div ng-switch-when="admin">You're admin.</div>
  <div ng-switch-when="moderator">You're moderator.</div>
  <div ng-switch-when="user">You're a user.</div>
  <div ng-switch-default>You're a guest.</div>
</div>

Comments

0

You don't need to use any switch statement.

<div ng-if="app.currentUser.role">
  <div>You're {{app.currentUser.role}}.</div>
</div>

<div ng-if="!app.currentUser.role">
  <div>You're a guest.</div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.