如何使用groupBy过滤器和输入上的ng-model绑定实现角度嵌套的ng-repeat

时间:2015-05-11 00:10:03

标签: angularjs

我试图创建一个嵌套的ng-repeat循环。它使用angular-filter中的groupBytoArray过滤器。

问题是我在嵌套数组中有一个可编辑的输入字段。没有实施"跟踪"在每次键入时更改ng-repeats时,它会失去焦点as described in this issue

如果我尝试在重复上放置track by,它会断开并显示许多具有空值的字段。有没有办法在这种情况下正确实现track by,以便重复显示正确,我可以键入输入字段而不会失去焦点?

这是一个例子,如果你运行它,你会在编辑输入时看到你失去焦点:



var app = angular.module('App', ['angular.filter']);

app.controller('MainCtrl', function() {

  this.Parts = [{
    Id: 1,
    ShortDescription: "Premium Shocks",
    SupplierSku: "ZXU3322",
    SellPrice: 110,
    SellPriceInclGst: 130,
    ProfitExclGst: 10,
    SupplierName: 'Super Sports',
    Quantity: 3
  }, {
    Id: 2,
    ShortDescription: "Spanner",
    SupplierSku: "4444",
    SellPrice: 44,
    SellPriceInclGst: 130,
    ProfitExclGst: 10,
    SupplierName: 'Bobs Parts',
    Quantity: 1
  }, {
    Id: 3,
    ShortDescription: "Spark Plugs",
    SupplierSku: "xxxxx",
    SellPrice: 10,
    SellPriceInclGst: 130,
    ProfitExclGst: 10,
    SupplierName: 'Bobs Parts',
    Quantity: 5
  }]


});

<html>

<head>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.4/angular-filter.min.js"></script>
</head>

<body ng-app="App">

  <table class="table" ng-controller='MainCtrl as main'>
    <thead>
      <tr>
        <th>Short Descriptin</th>
        <th>SKU</th>
        <th>Qty</th>
        <th>Unit Price</th>
        <th>Total</th>
        <th>Total + GST</th>
      </tr>
    </thead>

    <tbody ng-repeat="supplier in main.Parts | groupBy:'SupplierName' | toArray:true | orderBy:'$key'">

      <tr class="title-display-row">
        <td colspan="6">{{ supplier.$key }}</td>
      </tr>

      <tr ng-repeat="item in supplier track by $index">
        <td>{{ item.ShortDescription }} {{ key }}</td>
        <td>{{ item.SupplierSku }}</td>

        <td class="field-cell">
          <div class="field-wrap">
            <input type="text" name="quantity[$index]" ng-model="item.Quantity" />
          </div>
        </td>
        <td>{{ item.SellPrice | currency }}</td>
        <td>Total</td>
        <td>Total-gst</td>
      </tr>
    </tbody>
  </table>
</body>

</html>
&#13;
&#13;
&#13;

任何建议都非常感谢。

1 个答案:

答案 0 :(得分:2)

万一有人遇到与此问题相同的问题......解决方法是删除toArray|true过滤器。

然后,我使用{{ supplier.$key }}而不是使用{{ Supplier[0].SupplierName }}访问供应商名称。因为循环中的每个supplier都是具有相同供应商名称的项目数组,因此我可以采用第一个并使用它。