2014-04-03 34 views
1

我想有條件地顯示一個基於存儲在父範圍內的布爾值的指令。我無法弄清楚爲什麼以下不起作用。通過,「不工作」我的意思是既不顯示指令。Angular JS:ng開關布爾不工作

<ul class="nav navbar-nav pull-right" ng-switch="userIsAuthenticated"> 
    <account-item item="accountMenuItem" ng-repeat="accountMenuItem in anonymousMenuItems" ng-switch-when="false"></account-item> 
    <account-item item="accountMenuItem" ng-repeat="accountMenuItem in authenticatedMenuItems" ng-switch-when="true"></account-item> 
</ul> 

無論指令都表現得想過「userIsAuthenticated」在我的測試情況下被設置爲「假」。如果我在指令上面添加{{userIsAuthenticated}},則按預期輸出'false'。

我也試過這樣:

<ul class="nav navbar-nav pull-right" ng-switch={{userIsAuthenticated}}> 
    <account-item item="accountMenuItem" ng-repeat="accountMenuItem in anonymousMenuItems" ng-switch-when={{false}}></account-item> 
    <account-item item="accountMenuItem" ng-repeat="accountMenuItem in authenticatedMenuItems" ng-switch-when={{true}}></account-item> 
</ul> 

如果我刪除條件NG-開關時,從他們要麼會顯示指令屬性。所以我知道問題是我的切換。

+0

您可以顯示'account-item'指令中的內容嗎? – raina77ow

回答

2

你的NG-開關的使用工作在這個簡化的演示,當然沒有你account-item指令: http://plnkr.co/AppN8xmFeIwjaP631lj7

在沒有看到代碼account-item,這是很難猜測可能與它進行干擾。您可以考慮使用ng-if來處理顯示一個或另一個項目。

<ul> 
    <div ng-if="!userIsAuthenticated">Content when not authenticated</div> 
    <div ng-if="userIsAuthenticated">Content when authenticated</div> 
</ul> 

更新 另外,還要確保你綁定的,而不是一個原始的布爾值,對象屬性。像:user. authenticated

+0

我在這個[Plunkr](http://plnkr.co/edit/cy8AfaBTlRwsEplHTBer?p=preview)中爲這些項目添加了一個(非常簡單的)'ng-repeat',似乎工作正常。所以'account-item'應該是這裏的關鍵。 – raina77ow

1

由於ngSwitchWhen有800優先級,你需要一個更高的優先級順序設置爲自定義指令(即account-item),它由ngSwitchWhen指令被處理之前進行編譯。例如:

.directive('accountItem', function() { 
    return { 
     ... 
     priority: 900, 
     ... 
    }; 
});