使用ng-switch和控制器变量

时间:2022-09-18 19:41:09

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.

我正在尝试在控制器变量上使用ng-switch,但它没有按预期工作,或者我遗漏了一些东西。我想打开控制器中定义的user_id。

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>

1 个解决方案

#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.

您正在以错误的方式使用ng-switch。您必须与在ng-switch初始化参数中使用的表达式保持一致。这是使用交换机匹配的正确方法,站在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.

由于user_id不是表达式,因此您的示例不起作用。

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

我建议你使用ng-if,这似乎更适合你的情况(如果我理解你想要的):

  <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

#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.

您正在以错误的方式使用ng-switch。您必须与在ng-switch初始化参数中使用的表达式保持一致。这是使用交换机匹配的正确方法,站在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.

由于user_id不是表达式,因此您的示例不起作用。

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

我建议你使用ng-if,这似乎更适合你的情况(如果我理解你想要的):

  <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

相关文章