2015-07-11 58 views
0

我想在控制器變量上使用ng-switch,它不像預期的那樣工作,或者我缺少一些東西。我想打開控制器中定義的user_id使用ng-switch與控制器變量

這裏是一個plunkr

控制器

$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> 
+0

你普拉克用一個很老的版本angularjs的'1.0.5'。這是故意的,還是可以使用新版本? – lostintranslation

+0

@lostintranslation不是故意的,我在1.3 – user2954587

回答

1

你在錯誤的道路使用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> 

由於user_id不是表達式,所以您的考試不起作用。

我建議你使用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

相關問題