Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
885 views
in Technique[技术] by (71.8m points)

angularjs - ng-repeat a single element over nested objects

Say I have an object with keys corresponding to products and values corresponding to objects which in turn have keys corresponding to price points at which those products have sold, and values corresponding to amount sold.

For example, if I sold 10 widgets at $1 and 5 widgets at $2, I'd have the data structure:

{ 'widget': {'1': 10, '2': 5} }

I'd like to loop over this structure and generate rows in a table such as this one:

thing   price  amount
---------------------
widget  $1     10
widget  $2     5

In Python it's possible to nest list comprehensions to traverse lists data structures like this. Would such a thing be possible using ng-repeat?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about this?

http://plnkr.co/edit/ZFgu8Q?p=preview

Controller:

$scope.data = {
  'widget1': {
    '1': 10,
    '2': 5
  },
  'widget2': {
    '4': 7,
    '6': 6
  }
};

View:

<div ng-controller="MyCtrl">
    <table>
      <thead>
        <tr>
          <td>thing</td>
          <td>price</td>
          <td>amount</td>
        </tr>
      </thead>
      <tbody ng-repeat="(productName, productData) in data">
        <tr ng-repeat="(price, count) in productData">
            <td>{{productName}}</td>
            <td>{{price|currency}}</td>
            <td>{{count}}</td>
        </tr>
      </tbody>
    </table>
</div>

Output:

thing   price   amount
----------------------
widget1 $1.00   10
widget1 $2.00   5
widget2 $4.00   7
widget2 $6.00   6

This would output a tbody per product (thanks to Sebastien C for the great idea). If needed, you can differentiate between the first, middle and last tbody (using ng-repeat's $first, $middle and $last) and style them with ng-class (or even native CSS selectors such as :last-child -- I would recommend ng-class though)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...