سؤال

lets say i have 2 collections

var products = [{Name : "p1", Id : 1}, {Name : "p2", id : 2}];
var locSales = [
 {LocName : "Loc1", Sales : [{Id : 1, Value : 23}, {Id : 2, Value : 54}]}
 {LocName : "Loc2", Sales : [{Id : 1, Value : 78}, {Id : 2, Value : 90}]}
];

i bind them to the controllers scope as

$scope.products = products;
$scope.locSales = sales;

i want to create a table out of this data with structure as follows

Loc Name | P1 | P2
Loc1     | 23 | 54
Loc2     | 78 | 90

to do this what iam doing now is to change the Sales property of locSales to the following structure

var locSales = [
     {LocName : "Loc1", Sales : {"1" : 23, "2" : 54}}
     {LocName : "Loc2", Sales : {"1" : 78, "2" : 90}}
    ];

so that i can then bind to the specific id like this

<table>
 <tr >
  <td>Loc name</td>
  <td ng-repeat="p in products">{{p.Name}}</td>
 </tr>
 <tr ng-repeat="s in locSales">
  <td>{{s.LocName}}</td>
  <td ng-repeat="p in products">
   {{s.Sales[p.Id]}}
  </td>
 </tr>
<table>

is there a better way of achieving this using some other way in angular js.

I Need to bind to an element of specific Id inside a collection

The process i have described here is repetitive and consumes resources plus dosent look good.

هل كانت مفيدة؟

المحلول

Assuming the array order is same for both products and locSales.Sales you could do:

<tr ng-repeat="s in locSales">
  <td>{{s.LocName}}</td>
  <td ng-repeat="sale in s.Sales">
    {{sale.Value}}
  </td>
</tr>

DEMO

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top