lightfuze
lightfuze

Reputation: 23

Access multiple items in multiple arrays from JSON using AngularJS

I'm building a phone directory app using AngularJS with JSON data. I'm new to AngularJS and JSON.

I went through the "Phonecat" tutorial on the AngularJS site and was able to build a test directory with JSON data that was similar to the tutorial.

I hit a roadblock using what I learned there and trying to build something with real data; the JSON objects have multiple arrays and I've not been able to figure out how to access the data in the arrays...

I tried to replicate my issue here: http://jsfiddle.net/4ykNX/

Thanks in advance!

//employee.json
{
    "resultTruncated": false,
    "containsSecureData": false,
    "entries": [
        {
            "type": "employee",
            "firstName": "Any",
            "lastName": "One",
            "address": [
                {
                    "streetOne": "123 Long Street",
                    "streetTwo": "Big Building",
                    "streetThree": "Room 456",
                    "city": "City",
                    "state": "ST",
                    "zip": "12345"
                }
            ],
            "phone": [
                {
                    "area": "111",
                    "number": "222-3333",
                    "extn": "444"
                }
            ],
            "email": "[email protected]"
        }
    ]
}

Upvotes: 1

Views: 10799

Answers (1)

Brian Lewis
Brian Lewis

Reputation: 5729

You are trying to set $scope.employees to data, when it should be data.entries

'use strict';

function EmpListCtrl($scope, $http) {
    $http.get('employees.json').success(function(data) {
    $scope.employees = data.entries;
  });
}

Then you need to reference employee.phone instead of phone:

<div ng-app>
    <div ng-controller="EmpListCtrl">
        <h1>Employees</h1>
        <ul>
            <li ng-repeat="employee in employees">
                {{employee.lastName}}, {{employee.firstName}}<br/>
                <a href="mailto:{{employee.email}}">{{employee.email}}</a>
                <ul>
                    <li ng-repeat="num in employee.phone">
                        {{num.area}}-{{num.number}}-{{num.extn}}
                    </li>
                </ul>
            </li>
        </ul>
    </div>
</div>

Here's a plnkr: http://plnkr.co/edit/L2nMu0?p=preview

Upvotes: 5

Related Questions