Pablo Francesca Pablo Francesca - 5 months ago 8
JSON Question

Angularjs - Instantiate array from JSON

I am merely trying to populate an array from an $http request and display the results in a table. Using Firebug, it seems to me that the data is being retrieved properly. See pictures for results.
DOM Results

Firebug Results

<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script>

var app = angular.module('myApp', []);

app.controller('ContactsController', function ($scope, $http)
{ var self = this; //added after initial post.
this.contactList = [];
this.InitiateContactList = function(arrayContacts) //this.InitiateContactList doesn't work?
{ for(i = 0; i < arrayContacts.length; i++)
this.contactList.push(arrayContacts[i]);
};

$http({
method: 'GET',
url: 'someurl', //pseudoCode
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response)
{ if(angular.isArray(response.data))
{ //this.contactList = response.data; //is this working properly?
self.contactList = angular.fromJson(response.data);
//this.InitiateContactList(response.data);
}
}, function errorCallback(response) {
});
});

app.controller('ActionsController', function ($scope, $http)
{
});

</script>
</head>
<body ng-controller="ActionsController as ActCtrl">

<div ng-controller="ContactsController as ContactsCtrl">
<table
<tr><th Email</th>
<th>Name</th>
<th>Frequency</th></tr>
</table>
<div ng-repeat="Contact in ContactsCtrl.contactList">
<table >
<tr><td>{{Contact.Email}}</td><td>test name</td><td>{{Contact.Frequency}}</td></tr>
</table>
</div>
</div>
</body>
</html>


this.contactList = angular.fromJson(response.data); seems to be working. The DOM array is populated as expected, but the ng-repeat doesn't seem to be working. I've done this procedure a couple other times in other contexts and it has worked as expected. What am I missing?

Update: The Batarang extension in Chrome shows the following:
Batarang

Is it normal to have the index 'Contact' showing like that?

Answer

In your ContactsController, do this

var self = this; 

Now use self instead of all this in your controller:

$http({
    method: 'GET',
    url: 'someurl', //pseudoCode
    headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
}).then(function (response) {
    self.contactList = angular.fromJson(response.data);
});

Hope that helps.