0

I'm trying to use ng-switch on a controller variable and it's not working as expected or I am missing something. I'd like to switch on the user_id which is defined in the controller.

Here is a plunkr

Controller

  $scope.user_id = "5";

  $scope.messages = [
    {id: 1, body: "Scope User Message", sent_messageable_id: 5},
    {id: 2, body: "Other Message", sent_messageable_id: 6}
  ]

HTML

  <div ng-repeat="message in messages">
    <div ng-switch on="message.sent_messageable_id">
      <div ng-switch-when="user_id">
        <!-- should be getting called but never does-->
        {{ message.body }}
      </div>
      <div ng-switch-default>
        {{ message.body }}
      </div>
      <div 
    </div>
  </div>
2
  • Your plunk is using a very old version of angularjs '1.0.5'. Is that on purpose, or can you use a new version? Commented Jul 11, 2015 at 21:30
  • @lostintranslation not on purpose, I'm on 1.3 Commented Jul 11, 2015 at 21:31

1 Answer 1

1

You are using ng-switch in the wrong way. You have to be coherent with the expression that you use in the ng-switch initialization parameter. This is the correct way to use switch matching, standing to AngularJS doc.

<ANY ng-switch="expression">
  <ANY ng-switch-when="matchValue1">...</ANY>
  <ANY ng-switch-when="matchValue2">...</ANY>
  <ANY ng-switch-default>...</ANY>
</ANY>

Since user_id is not the expressione your exampole will not work.

I suggest you to use ng-if, that seems more suitable to your case (if I've understand what you want):

  <div ng-repeat="message in messages">
    <div>
      <div ng-if="user_id">
        <p>NOW getting called</p>
        {{ message.body }}
      </div>
      <div ng-if="!user_id">
        {{ message.body }}
      </div>
    </div>
  </div>

PLNKR

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

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.