I am having troubles trying to return an object within an array in an if-else loop within a function.
Basically, I want to return the first item object in the array and the getItemDetails will run and get the first item and then if triggered again, it will clear the array and write the other item object to it.
I have a service called ItemService that contains the following function:
getItemDetails: function(details) {
if (itemDetails.length == 0) {
itemDetails.push(details);
return itemDetails;
console.log(itemDetails[0].name);
}
else {
itemDetails = [];
itemDetails.push(details);
console.log (itemDetails[0].name);
return itemDetails;
console.log(itemDetails[0].name);
}
This is the controller:
.controller("itemListingDetailCtrl", function ($scope, itemService, $stateParams, $state)
{
$scope.name = itemService.getItemDetails()[0].name;
$scope.description = itemService.getItemDetails()[0].desc;
})
Here is the accordion that contains the onSelectItems function that takes a JSON object as a parameter.
<ion-item class="item-accordion"
ng-repeat="item_type in item.subcategories"
ng-show="isGroupShown(beer)"
ng-click="onSelectItems(item_type)">
{{item_type.name}}
</ion-item>
Whenever it runs, I can see in the console logs that I receive the following error:
Cannot read property 'name' of undefined
at Object.getItemDetails
If I remove the if else loop and simply push the item to the array and return itemDetails, it will give me the correct first item in the array. Any ideas?
Thanks in advance.