2013-04-30 54 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