访问ng-repeat的第一个元素

时间:2013-08-28 03:21:44

标签: javascript angularjs

如何访问后续每一行中的第一个数量和价格值:

在这种情况下,“选择”是由一些单选按钮设置的变量。

<tr ng-repeat="(qty, price) in product.sizes[selection]">
  <td><input type="radio"> <% qty %></td>
  <td><% price %></td>
  <td>You save (actual calc more complex) {{price - FIRSTROWPRICE}}</td>
</tr>

我可以通过使用$ first / ng来防止最后一行进行数学运算,如果没有问题那么。

以下是数据:

   {
    "name": "The product",
    "sizes": {
      "2x2": { "100": "55", "200": "80", "300": "95"},
      "3x3": { "100": "155", "200": "180", "300": "195"}
      }
  }

使用一些单选按钮选择“选择”参数:

<form>
  <div class="radio" ng-repeat="(size, data) in product.sizes">
    <label>
      <input type="radio" value="{{ size }}" ng-model="$parent.selection"> {{ size }}
    </label>
  </div>
</form>

1 个答案:

答案 0 :(得分:1)

这是一个解决方案:

首先,您需要在示波器上使用一个函数来跟踪哪个键首先出现:

// in controller
$scope.setFirst(key, isFirst) {
    if(isFirst) { $scope.first = key; }
};

现在,在您看来,您这样做:

<tr ng-repeat="(qty, price) in product.sizes[selection]" ng-init="setFirst(qty,$first)">
  <td><input type="radio"> <% qty %></td>
  <td><% price %></td>
  <td>You save (actual calc more complex) {{price - product.sizes[first]}}</td>
</tr>

或者,您可能希望仅通过存储第一个价格来减少计算次数:

$scope.setFirstPrice(price, isFirst) {
    if(isFirst) { $scope.firstPrice = price; }
}

<tr ng-repeat="(qty, price) in product.sizes[selection]" ng-init="setFirstPrice(price,$first)">
  <td><input type="radio"> <% qty %></td>
  <td><% price %></td>
  <td>You save (actual calc more complex) {{price - product.sizes[first]}}</td>
</tr>

您选择哪种方式取决于您的需求。关键步骤是使用控制器上的功能来跟踪首先呈现的价格。

请注意:

在JavaScript中,hashmap对象中的参数顺序为无法保证!浏览器可以选择以不同的顺序输出项目,因此您可能无法始终首先获得预期的项目。如果订单非常重要,请考虑将数据结构重新排列为对象数组,例如:

"sizes": {
    "2x2": [{ price:"100", qty:"55"}, {price:"200", qty:"80"}, {price:"300", qty:"95"}],
    // etc
}

如果sizes的顺序很重要,您将要对该对象执行相同操作。

可能没问题,只需确保在要支持的所有浏览器中进行彻底测试。

相关问题