【问题标题】:Can I use ng-switch with ng-repeat?我可以将 ng-switch 与 ng-repeat 一起使用吗?
【发布时间】:2019-10-03 09:15:08
【问题描述】:

我有一个名为$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)"}

我想使用 ng-switch 来一个一个地显示每个部分。这是我尝试过的:

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

然后next()函数:

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

但这似乎不太奏效。如果我删除 ng repeat 并手动添加部分,它似乎可以工作。有没有办法将ng-repeatng-switch 一起使用?

【问题讨论】:

    标签: angularjs angularjs-ng-repeat angularjs-ng-switch


    【解决方案1】:

    ng-switchng-repeat 不会一一显示每个部分。一种解决方案是在 ng-repeat 中使用 filter,如下所示:

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

    查看工作演示:DEMO

    【讨论】:

      猜你喜欢
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      • 2014-09-28
      相关资源
      最近更新 更多