Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over inner object's properties in an AngularJS template?

I'm in the process of learning AngularJS. I would like to print out a list of objects and iterate over one of the object's inner object's properties. This looked like a standard procedure of using nested loops, however, it doesn't appear to be so simple.

My Controller is setup below. Essentially, it is a list of random vehicles.

var vehicleApp = angular.module("vehicleApp", []);

vehicleApp.controller('VehicleController', function ($scope) {
    $scope.vehicles = [{
        id: 0,
        name: "car",
        parts: {
            wheels: 4,
            doors: 4
        }
    }, {
        id: 1,
        name: "plane",
        parts: {
            wings: 2,
            doors: 2
        }
    }, {
        id: 2,
        name: "boat",
        parts: {
            doors: 1
        }
    }];
});

I'd like to output the vehicles as such:

car
 - wheels (4)
 - doors (2)

plane
 - wings (2)
 - doors (2)

boat
 - doors (1)

My template that I used was setup as such:

<div ng-app="vehicleApp" ng-controller="VehicleController">
    <p ng-repeat="vehicle in vehicles">
        {{ vehicle.name }}
    </p>
    <ul>
        <li ng-repeat="(attribute, value) in vehicle.parts">
            {{attribute}} ({{value}})
        </li>
    </ul>
</div>

This produces a list of the vehicles, but not the sub lists of the parts inner object.

Interestingly, enough, when I use {{ vehicle.parts }} it returns a JSON string of the parts inner object. Does AngularJS treat it as a string and hence, it is unable to print out the properties of the parts object?

like image 534
Pete Avatar asked Dec 16 '13 21:12

Pete


1 Answers

You didn't enclose the second ngRepeat in the first one:

<div ng-app="vehicleApp" ng-controller="VehicleController">
    <p ng-repeat="vehicle in vehicles">
        {{ vehicle.name }}
        <ul>
            <li ng-repeat="(attribute, value) in vehicle.parts">
                {{attribute}} ({{value}})
            </li>
        </ul>
    </p>
</div>
like image 108
Blackhole Avatar answered Oct 10 '22 10:10

Blackhole