2013-04-30 58 views
2

我試圖用ng-switch來組合一種標籤式菜單。AngularJS ng-switch-when表達式

我設置在我的Ctrl鍵(流)選項卡,並跟蹤當前選定的一個作爲選擇的:

app.controller("StreamCtrl", function($scope) { 
$scope.streams = [{ 
    title: 'latest', 
    icon: 'time', 
    data: "Hi, I'm data." 
}, { 
    title: 'popular', 
    icon: 'fire', 
    data: "Hi, I'm data too!" 
}]; 

$scope.selection = $scope.streams[0]; 

$scope.getCurrentStreamIndex = function(){ 
    // Get the index of the current stream given selection 
    return $scope.streams.indexOf($scope.selection); 
}; 

// Go to a defined stream index 
$scope.goToStream = function(index) { 
    if($scope.streams[index]) { 
     $scope.selection = $scope.streams[index]; 
    } 
}; 
}); 

在我看來,(index.html的),我用NG-重複創建每個標籤的容器:

<section class="streams" ng-controller="StreamCtrl" ng-switch="stream.title == selection.title"> 
     <section class="stream" ng-switch-when="true" ng-repeat="stream in streams"> 
      {{stream.title}} 
      <div class="loaderContainer"><div class="loader"></div></div> 
     </section> 
    </section> 

我遇到的問題是使用我的ng-switch-when語句,因爲它不接受表達式。

如果我可以設置ng-switch-when="{{stream.title}}"那麼我相信我可以使用ng-switch="selection.title",一切都會好的。

雖然我會如何構造一個ng-switch表達式來匹配動態生成的列表?

+1

,哪裏是「流」來自?我看到在你的控制器中定義的「選擇」,但「流」沒有被定義,直到「ng-repeat」爲止,據我所知。 – Jonah 2013-04-30 23:49:05

+0

我不太瞭解ng-switch何時評估它的表達式以及它的評估範圍。你看到的是一個測試。我希望能夠在ng-switch-when的範圍內進行評估(在這種情況下也是ng-repeat),所以stream(來自ng-repeat)可能是一個可用的對象。 – 2013-04-30 23:55:30

+0

不是100%確定,但我不認爲它是這樣的。我會嘗試重組,假設除了ng-repeat語句之外,「stream」將不可用。 – Jonah 2013-05-01 00:03:10

回答

3

好吧,看看這個,我想應該給你足夠的繼續下去:

http://jsbin.com/okukey/1/edit

新的HTML:

<div ng-controller="StreamCtrl"> 
    <section class="streams" ng-repeat="stream in streams"> 
     <section class="stream"> 
      {{stream.title}} 
      <div class="loaderContainer" ng-show="stream == selection"><div class="loader">SELECTED</div> 
     </section> 
    </section> 
    </div> 
在你的 「NG-開關」
+0

噢,好的,你用ng-show關掉了ng-switch。是的!這樣可行。非常感謝。我認爲ng-switch只是不起作用,而且必須有另一種方式來實現。 – 2013-05-01 00:52:26

+0

@Jonah:一個更簡潔的方法來替換'ng-switch'將會使用'ng-if'來代替,因爲它會從DOM中刪除錯誤的結果元素,就像'ng-switch-when'一樣。 'ng-show'和'ng-hide'保持DOM中的元素操作它們的CSS類,這意味着它們需要更多的資源。可能微不足道,但並非總是如此。 – 2015-02-06 16:30:15