krillebimbim krillebimbim - 1 month ago 7
AngularJS Question

How do I access the nested categories data and reference it in my controller?

I'm creating an Ionic app with the WP Rest API. I have returned the post data but I'm furthermore looking to get the category name. The JSON data for the posts only contains the category ID. I am trying to access the category ID and reference it in my controller to get the categories data in order to get the category name via the ID.

My controller looks like this:
svampeApp.controller('PostCtrl', function ($scope, svampeApi, $stateParams) {

//Individual Post Controller
console.log("$stateParams", $stateParams);

$scope.posts = [];
$scope.categoryId = [];

$scope.id = $stateParams.id;

svampeApi.getPostData($scope.id).then(function (succ) {
$scope.posts = succ;
$scope.categoryId = succ.categories;
}, function(err) {
console.log('Error: ', err);
});

console.log("Category Object", $scope.categoryId);

//Getting the category ID to display the category name
$scope.categories = [];

svampeApi.getCategoryData($scope.categoryId).then(function (succ) {
$scope.categories = succ;
}, function(err) {
console.log('Error: ', err);
});

});


With this line I should get the category ID as it is stored in the Post object:

$scope.categoryId = succ.categories;


However, when I make my second api call for the category name using the ID, I get an error.

svampeApi.getCategoryData($scope.categoryId).then(function (succ) {
$scope.categories = succ;
}, function(err) {
console.log('Error: ', err);
});


How do I save the category ID of the individual post in the scope so I can access it in my second api call? The categories include the name of the category, which I want to access in my view via:

<p>
{{categories.name}}
</p>


The category object is empty:

Category Object []


I hope you can help me.

Answer

Please clarify: Are you getting the category name from the server or is it embedded in the JSON from the first server call (that includes category ID)? I don't see and REST/Ajax calls. NOTE: Your server calls are asynchronous so you cannot call to get the category name from server until the category id server call is guaranteed complete. This means you need to chain your promises.