nofear87
nofear87

Reputation: 869

How can I show dynamically "nested" objects with ng-repeat

I have a Object with dynamic content, for example:

$scope.test = [
{
   "name" : "device1",
   "params" : [{"freq1" : "144"},{"freq2" : "160"}]

},
{
   "name" : "device2",
   "params" : [{"freq3" : "144"}]

}]

I use ng-repeat to show the content:

<li ng-repeat="(key,value) in test">{{key}}:{{value}}<li>

But how can i use key value for params?

<li ng-repeat="(k,v) in test.params">{{k}}:{{v}}<li>

isn't working :-(

http://jsfiddle.net/nofear87/kyGa3/1/

Edit:

$scope.test = [
{
   "name" : "device1",
   "params" : [{"freq1" : "144"},{"freq2" : "160"}],
   "category" : "test-category"

},
{
   "name" : "device2",
   "params" : [{"freq3" : "144"}],
   "vendor" : "intel"

}]

Upvotes: 0

Views: 1608

Answers (3)

vusan
vusan

Reputation: 5331

calling function from template.
html:

<tr ng-repeat="(key, value) in device">
    <td><strong>{{key}}</strong></td>
    <td>{{val(value)}}</td>
</tr>

js

    $scope.val = function(value) {
        if(typeof value == 'string') {return value}
        else if(typeof value == "object") {
            var values="";
            value.forEach(function(val,index){

                if(val.name) {values+=val.name}
                else if(val.freq) {values+=val.freq+", "}
                 else if(val.maxFreq) {values+=val.maxFreq+", "}
            });
            return values;
    }
}

Upvotes: 1

Florian Orben
Florian Orben

Reputation: 96

You're going to have to add another level of ng-repeatto iterate display the test.params' individual keys and values - here's a modified version of your fiddle:

<ul>
    <li ng-repeat="(key, value) in test">
        {{value.name}}
        <ul ng-repeat="(k, v) in value.params">
            <li ng-repeat="(paramKey, paramVal) in v">{{paramKey}} -&gt; {{paramVal}}</li>
        </ul>
    </li>
<ul>

This will output:

  • device1
    • freq1 -> 144
    • freq2 -> 160
  • device2
    • freq3 -> 144

Also please note that your fiddle is missing the square brackets to turn $scope.testinto an array

Upvotes: 2

Slaven Tomac
Slaven Tomac

Reputation: 1550

Something like this

http://jsfiddle.net/kyGa3/2/

<body ng-app="app" ng-controller="projects"> 

<table class="table">
    <tbody>
        <tr ng-repeat="(key, value) in device">
            <td><strong>{{key}}</strong></td>
            <td>{{value}}</td>
        </tr>
        <div ng-repeat="item in device.params">
            <div ng-repeat="(k, v) in item">
                <strong>{{ k }}</strong>
                {{ v }}
            </div>
        </div>
    </tbody>
</table>

</body>

device.params is array...

Upvotes: 0

Related Questions