【问题标题】:ng-switch inside ng-repeat what am I missing?ng-repeat 里面的 ng-switch 我错过了什么?
【发布时间】:2014-07-21 01:28:30
【问题描述】:

我有一个页面正在使用我的 ClientController 和模板来显示从服务器检索到的信息表。对于每个数据集合,我希望有 2 个表格行,一个始终显示,另一个仅在单击第一个时显示。

我已经简化了代码,因为这里还有更多内容,但我认为没有什么会影响到这一点。

我的 HTML 看起来像

<table>
  <tbody ng-repeat="session in sessions" ng-switch on="sessionID">
    <tr>
      <td>{{session.test_name}}</td>
      <td><a ng-click="showID(session.session_id)">view {{session.session_id}}</a></td>
    </tr>
    <tr class="pop-open" ng-switch-when="session.sessionID">
      <td colspan="2">
        {{session.session_ID}} and more details
      </td>
    </tr>
  </tbody>
</table>

在我的 controllers.js 中我有

.controller('ClientController', ['$scope', function($scope) {
  $scope.showID = function(sessionID){
    $scope.sessionID = sessionID
    alert($scope.sessionID)
  }
}])

会弹出带有正确 ID 的警报,但表格行未按我预期的那样显示。

【问题讨论】:

    标签: javascript angularjs ng-switch


    【解决方案1】:

    对于这个简单的用例场景,您实际上不需要 ng-switch,在会话中添加 showDetails 之类的变量,应该可以做到...

    <table>
      <tbody ng-repeat="session in sessions">
        <tr>
          <td>{{session.test_name}}</td>
          <td><a ng-click="session.showDetails = !session.showDetails">view details</a></td>
        </tr>
        <tr class="pop-open" ng-show="session.showDetails">
          <td colspan="2">
            {{session.session_ID}} and more details
          </td>
        </tr>
      </tbody>
    </table>
    

    一次只打开一个

    <table>
      <tbody ng-repeat="session in sessions">
        <tr>
          <td>{{session.test_name}}</td>
          <td><a ng-click="showDetailsOfId = session.session_id">view details</a></td>
        </tr>
        <tr class="pop-open" ng-show="showDetailsOfId == session.session_id">
          <td colspan="2">
            {{session.session_ID}} and more details
          </td>
        </tr>
      </tbody>
    </table>
    

    【讨论】:

    • 感谢@HarishR 这行得通,但不能提供完整的解决方案 - 显示的细节将非常丰富,所以我想一次只打开一个,这就是我想使用 ng-切换。
    • 在这种情况下,在 $scope 而不是 session 上维护一个变量.. 检查更新的答案
    • 那行得通 - 谢谢 - 下次我会在回答之前考虑一下!
    猜你喜欢
    • 2013-11-23
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多