Reputation: 967
In an AngularJS controller i have created a function which makes a JSONP request. This request returns a JSONP object which has the following format.
[{
"Domain_1":{
"Notes":"This information can be usefull for generic information",
"Contacts":[
{
"ContactName":"P. rimary",
"ContactPhone":"+31 612 273 88"
}
]
},
"Domain_2":{
"Notes":"This information can be usefull for generic information",
"Contacts":[
{
"ContactName":"S. secondary",
"ContactPhone":"+31 612 273 88"
}
]
}
}];
The object is returned successfully when making the JSONP request in the following function. ($scope.method and $scope.domainName are set at scope level) What i want is to achieve is to select a specific part of the JSON data matching the value in $scope.domainName and assign this to a scope variable $scope.domainData.
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
// Only make JSONP request if domain name is known
if ($scope.domainName !== null) {
$http({method: $scope.method, url: $scope.url, timeout: 5000}).
success(function(data, status) {
$scope.status = status;
console.log("Data:") ; console.dir(data) ;
console.log("Domain Name" + $scope.domainName) ;
$scope.domainData = data[$scope.domainName] ;
console.log("DomainData: ") ;
console.dir($scope.domainData) ;
}).
error(function(data, status, headers, config) {
$scope.domainData = null ;
$scope.status = status;
console.log("$scope.fetch failed" + $scope.status + " :: " + data) ;
});
} else {
console.log("Shame... nothing to do..... ") ;
}
};
When the code is executed the Domain Name is "Domain_1" and data contains (shown in console);
0: Object
Domain_1: Object
Contacts: Array[1]
0: Object
ContactName:"P. rimary"
ContactPhone:"+31 612 273 88"
...
But $scope.domainData is undefined. How can make this selection work correctly?
Upvotes: 0
Views: 118
Reputation: 5236
Your response object appears to be an array at the top level, based on the encapsulating square brackets. That means you won't be able to directly dereference it with the domain name. One approach to remedy this would be something like the following in your success function:
$scope.domainData = data[0][$scope.domainName];
This is of course only advisable to hardcode that 0
if you're always sure your response object will be an array of length 1 (as it is in your example). If that will not always be the case, you may have to implement some kind of iterative traversal looking for a matching property.
Upvotes: 1
Reputation: 2359
to access the data in the response you should access the data property of the response.
...
$http({method: $scope.method, url: $scope.url, timeout: 5000}).
success(function(response, status) {
...
# With the latest versions of angularJs (I don't know in which
# version was that), the data is in the
# response's data property
$scope.domainData = response.data[$scope.domainName] ;
...
Upvotes: 0