Lucas Raines
Lucas Raines

Reputation: 1315

AngularJS ng-switch-when expression

I'm trying to put together a sort of tabbed menu using ng-switch.

I set the tabs in my Ctrl (streams) and keep track of the currently selected one as selection:

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];
    }
};
});

And in my view (index.html), I use ng-repeat to create a container for each tab:

<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>

The problem I run in to is with my ng-switch-when statement, because it won't accept an expression.

If I could set ng-switch-when="{{stream.title}}" then I believe I could use ng-switch="selection.title" and all would be fine.

How would I structure an ng-switch expression though to match a dynamically generated list?

Upvotes: 2

Views: 11625

Answers (1)

Jonah
Jonah

Reputation: 16242

Ok, check out this out, I think it should give you enough to keep going:

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

New 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>

Upvotes: 3

Related Questions