使用AngularJS展开/合同表部分

Phi*_*ler 4 dom angularjs

我有一个HTML表,通过AngularJS绑定到数据.为简单起见,我们只说它有两列,CustomerId和CustomerName.

当用户点击该行(或加号,按钮,链接无关紧要)时,我想在该行下方展开一段,进行ajax调用,并显示结果数据.我还想崩溃先前扩展的行,如果有的话.

这看起来像是一个DOM操作任务,我知道如何在JQuery中完成它(或者至少可以解决它),但我想要正确地执行它(即"Angular Way").

joa*_*mbl 6

今天使用Angular实际上有点困难,但你有几个选择.

首先,我认为最具声明性的解决方案是<tr>使用正常状态,<tr>使用编辑状态:

<tr ng-show="edit"><td><input ng-model="model.name" ...
<tr ng-hide="edit"><td>{{model.name}} ...
Run Code Online (Sandbox Code Playgroud)

替代方案(实际上更简单)就是在列上执行此操作 <td>

<tr>
  <td ng-show="edit"><input ng-model="model.name" ... 
  <td ng-hide="edit">{{model.name}} ... 
</tr>
Run Code Online (Sandbox Code Playgroud)

这个更简单的原因是,在Angular的当前版本(1.0.x)中,您只能ng-repeat在单个根元素上执行(尽管看起来这将在v 1.2.x中更改:多元素指令).幸运的是,你被允许<tbody>在html中使用多个标签,所以这实际上是有效的:

<tbody ng-repeat="model in models"> 
  <tr ng-show="edit"><td><input ng-model="model.name" ...
  <tr ng-hide="edit"><td>{{model.name}} ...
<tbody>
Run Code Online (Sandbox Code Playgroud)

请注意,ng-hide仅使用隐藏dom中的元素.如果你担心性能(巨大的表或移动设备)ng-switch(或ng-if1.2.x)可能是一个更好的选择,因为它从dom中删除了隐藏的部分:

  <tbody ng-repeat="model in models" ng-switch="row.edit" ng-init="row={}">
    <tr ng-switch-when="true">
      <td><input type="text" ng-model="model.customerId" disabled /></td>
      <td><input type="text" ng-model="model.customerName" /></td>
      <td ng-click="row.edit=false">done</td>
    </tr>
    <tr ng-switch-default>
      <td>{{model.customerId}}</td>
      <td>{{model.customerName}}</td>
      <td ng-click="row.edit=true">edit</td>
    </tr>
  </tbody>
Run Code Online (Sandbox Code Playgroud)

更新:我添加了第三个使用ng-include的解决方案:

这种方法可能不是最具声明性的,但它的效果非常好.我创建了两个不同的行模板(这些模板可以是单独的文件,也可以像我的例子一样内联为ng-templates),然后我用它ng-include来切换两个模板.请注意,这没有额外的工作<tbody>:

<script type="text/ng-template" charset="utf-8" id="display.html">
  <td>{{model.customerId}}</td>
  <td>{{model.customerName}}</td>
  <td ng-click="row.edit=true">edit</td>
</script>

<script type="text/ng-template" charset="utf-8" id="edit.html">
  <td><input type="text" ng-model="model.customerId" disabled /></td>
  <td><input type="text" ng-model="model.customerName" /></td>
  <td ng-click="row.edit=false">done</td>
</script>

<table border="0">
  <tr>
    <th>CustomerId</th>
    <th>CustomerName</th>
    <th>Edit</th>
  </tr>

  <tr ng-repeat="model in models" 
      ng-include="{true:'edit.html',false:'display.html'}[row.edit]" 
      ng-init="row={edit:false}"></tr>
</table>
Run Code Online (Sandbox Code Playgroud)

我用ng-switch和ng-show/hide创建了一个简单的例子:http://plnkr.co/edit/6kBPIT0Z07ti4BtnGrXj