简体   繁体   中英

Access first element of ng-repeat

How can I access the first qty and price values in each subsequent row:

"selection" in this case is variable set by some radio buttons.

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

I can prevent that last row from doing the math by using $first/ng-if so no issues for that.

Here's the data:

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

And the "selection" param is selected using some radio buttons:

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

Here's one solution:

First, you need a function on the scope to track which key comes first:

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

Now, in your view, you do this:

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

Alternatively, you may want to reduce the number of calculations by just storing the first price:

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

and

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

Which you choose depends on your needs. The key step is using a function on the controller to track which price is being rendered first.

Please Note:

The order of parameters in a hashmap object is not guaranteed in JavaScript! It's possible for a browser to choose to output the items in a different order, so you may not always get the expected item first. If the order is really important, think about rearranging your data structure to be an array of objects, like:

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

If the order of sizes matters, you'll want to do the same with that object.

It might be fine, just make sure you thoroughly test in all the browsers you want to support.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM