angularjsangularjs-ng-repeatangularjs-ng-switch

Can I use ng-switch with ng-repeat?


I have an array called $scope.sectionList:

0: {id: "1", section_name: "About me (in detail)"}
1: {id: "2", section_name: "About me (single word)"}
2: {id: "3", section_name: "My freaky side (in detail)"}
3: {id: "4", section_name: "My freaky side (single word)"}
4: {id: "5", section_name: "Embarrassing (in detail)"}
5: {id: "6", section_name: "Embarrassing (single word)"}

I want to use ng-switch to display each section one by one. Here is what i have tried:

<div ng-switch="myVar">
  <div ng-repeat="section in sectionList" ng-switch-when='{{section.id}}' class="animate-switch-container">
    <div class="col-md-12 grid-margin stretch-card" >
      <div class="card">
        <div class="card-body" >
          <h4 class="card-title">{{section.section_name}} {{section.id}}</h4>
          <button type="button" class="btn btn-primary" ng-click="next(section.id)">Start</button>
        </div>
      </div>
    </div>
  </div>
  <div ng-switch-default>
    <h1>Switch to next section</h1>
    <button type="button" class="btn btn-primary" ng-click="next(1)">Start</button>
  </div>
</div>

and then next() function:

$scope.myVar = '';
$scope.next = function (myVar) {
  $scope.myVar = myVar;
}; 

But it doesnt seem too work. If I remove ng repeat and manually add sections it seems to work. Is there a way to use ng-repeat with ng-switch?


Solution

  • ng-switch with ng-repeat won't show each section one by one. One solution would be using filter in ng-repeat like this:

    <div ng-repeat="section in sectionList | filter: {id: myVar}" class="animate-switch-container">
        <div class="col-md-12 grid-margin stretch-card">
            <div class="card">
                <div class="card-body">
                    <h4 class="card-title">{{section.section_name}} {{section.id}}</h4>
                    <button type="button" class="btn btn-primary" ng-click="next(section.id)">Start</button>
                </div>
             </div>
        </div>
    </div>
    

    Check a working demo: DEMO