簡體   English   中英

Angular JS:ng-switch on boolean不工作

[英]Angular JS: ng-switch on boolean not working

我試圖根據存儲在父作用域中的布爾值有條件地顯示指令。 我無法弄清楚為什么以下不起作用。 通過,“不工作”我的意思是既沒有顯示指令。

 <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”設置為“false”,也沒有顯示任何指令。 如果我在指令上面添加{{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-switch-when屬性。 所以我知道問題是我的ng-switch。

您對ng-switch的使用在此簡化演示中有效,當然沒有您的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 user. authenticated

由於ngSwitchWhen的優先級為800,因此需要為自定義指令(即account-item )設置更高的優先級,以便在由ngSwitchWhen指令處理之前對其進行編譯。 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM