mobiusinversion
mobiusinversion

Reputation: 353

How to Bind to Variable Length Property in AngularJS

I have a table which is going to display results sent from the server, however the results themselves have a dynamic shape. There is also another API which provides the shape / schema of the nesting. So my HTML looks something like this:

 <tr ng-repeat="result in results">
     <td ng-repeat="path in schema.paths">{{result[path]}}</td>
 </tr>

Of course, this does not work since path may be one item, or it may be many items expressed as a dotted string. That is, path could be nesting1 which would work, or it could be nesting1.nesting2.nesting3 which would not work. How can I accommodate this use case without using the $compile service in JavaScript?

Upvotes: 0

Views: 147

Answers (2)

Kate Chumbarova
Kate Chumbarova

Reputation: 36

As mentioned above, get function should work. Alternatively you could flatten your 'result'. For example if there is an object: {'a': {'b': 3}} then flattened it would look like so: {'a.b': 3}

There are lots of implementations posted here, for example: flatten nested object

Upvotes: 0

Andrew Lahikainen
Andrew Lahikainen

Reputation: 370

If I understand this question correctly, I think there is a Lodash function that can help you here.

It's called get. Usage:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// => 3

_.get(object, ['a', '0', 'b', 'c']);
// => 3

_.get(object, 'a.b.c', 'default');
// => 'default'

For your case it might look something like:

controller.js

import { get } from 'lodash-es';

...

// Your controller code...

...

    this.getResultAtPath = path => get(this.results, path);

template.html

<tr ng-repeat="result in results">
     <td ng-repeat="path in schema.paths">{{ getResultAtPath(path) }}</td>
</tr>

If you don't want to take on the dependency, I suggest you take a look at their implementation for get.

Upvotes: 1

Related Questions