TerryLi
TerryLi

Reputation: 231

AngularJS data binding within another data binding

I just stepped into the AngularJS world, and need a solution for the application I am working on.

So here is the definition of the module.

var samplesApp = angular.module('samples', []);

samplesApp.controller('samplesController', function ($scope) {
   var jsonObj=
      [
         {"ACTION":"UPDATE","ID":"22","ROUTE":"0015"},
         {"ACTION":"DELETE","ID":"20","ROUTE":"0015"},
         {"ACTION":"UPDATE","ID":"19","ROUTE":"0015"}
      ]
    $scope.records = jsonObj;

    var columnNames = [];
    for (var key in jsonObj[0]) {
        columnNames.push(key);
    }

    $scope.columnNames = columnNames;

});

The $scope JSON object is a part of the output of the real data that comes from database. and I need to put these data into a table dynamically

The html is like

<table>
    <thead>
        <th data-ng-repeat="column in columnNames">{{column}}</th>
    </thead>
    <tr data-ng-repeat="record in records">
        <td data-ng-repeat="column in columnNames">{{ record.{{ column }} }}</td>
    </tr>
</table>

Because I have no idea what the column name is, so I made a process to get all the column names and push them into $scope.columnNames. and then bind it to the table header. There is no problem for this part. The issue is I don't know how to get the value coresponse to the specific column. I was trying to do it like this:

<td data-ng-repeat="column in columnNames">{{ record.{{ column }} }}</td>

But apparently it is not working.

Can someone give me some advice? really appreciate it.

Upvotes: 0

Views: 227

Answers (2)

GonchuB
GonchuB

Reputation: 705

Accessing with the record[column] operator is OK, but you could try this other alternative. In this example, the semantics of the code is a bit better, and you have less coupling (your rows just depend on the data, not the variable used in the header):

<table>
    <tr>
        <th data-ng-repeat="column in columnNames">{{column}}</th>
    </tr>

    <tr data-ng-repeat="record in records">
        <td data-ng-repeat="(key,value) in record">{{value}}</td>
    </tr>
</table>

Here's the working example with your data: http://plnkr.co/edit/CskLQ2ZZlYIURdNPXiZt?p=preview

Here's the Angular docs for the ngRepeat directive (look for "key, value")

Upvotes: 1

Mikke
Mikke

Reputation: 2167

Try using brackets, like this:

<tr data-ng-repeat="record in AllRecords">
    <td data-ng-repeat="column in columnNames">{{ record[column] }}</td>
</tr>

The expressions inside {{ }} (moustaches?) are evaluated pretty narrowly to how regular javascript is evaluated.

Upvotes: 2

Related Questions