Reputation: 15
Can someone please point out where I am making a mistake.
Its a very simple application that is meant to print out the "name" field in and array of Json objects, Which is done via the line :
{{ctrl.contact[0].results[0].name.first}}
or
{{ctrl.contact[1].results[0].name.first}}
(which in itself seems very convoluted)
I cannot get it to print out the name of each Json block individually by loop and here is what i have tried :
<div ng-repeat="i in ctrl.contact">
<span>{{ctrl.contact[i].results[0].name.first}}</span>
</div>
Im confident after spending a few hours tweaking and editing that my angular set up (app, controller etc) is fine.
code snippet below :
<html ng-app="ContactAppApp">
<head>
<title>My Contact App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
</head>
<body>
<div>
<div ng-controller="ContactAppController as ctrl">
<h1>{{ctrl.test}}</h1>
<div ng-repeat="i in ctrl.contact">
<span>{{ctrl.contact[0].results[0].name.first}}</span>
</div>
</div>
</div>
</body>
<script>
var app = angular.module("ContactAppApp", [])
app.controller("ContactAppController", ContactAppController);
function ContactAppController() {
this.test = "This text is generated by Angular";
this.contact = [
{
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "tony",
"last": "cruz"
},
"location": {
"street": "9813 north road",
"city": "edinburgh",
"state": "humberside",
"postcode": "E84 4YD"
}
}
]
},
{
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "Jack",
"last": "cruz"
},
"location": {
"street": "9813 north road",
"city": "edinburgh",
"state": "humberside",
"postcode": "E84 4YD"
}
}
]
}
]
}
</script>
</html>
Upvotes: 0
Views: 325
Reputation: 262
I would set up your array a little differently. Try something like this:
this.contact = {
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "tony",
"last": "cruz"
},
"location": {
"street": "9813 north road",
"city": "edinburgh",
"state": "humberside",
"postcode": "E84 4YD"
}
},
{
"gender": "male",
"name": {
"title": "mr",
"first": "Jack",
"last": "cruz"
},
"location": {
"street": "9813 north road",
"city": "edinburgh",
"state": "humberside",
"postcode": "E84 4YD"
}
}
]
}
Then in your ng-repeat, try something like this:
<div ng-repeat="item in contact.results">
<span>{{item.name.first}} {{$index}}</span>
</div>
If you are trying to track the index of the item in array, use $index, not i.
Upvotes: 0
Reputation: 2633
Try the following:
<div ng-repeat="i in ctrl.contact">
<span>{{i.results[0].name.first}}</span>
</div>
Upvotes: 1