我有麻煩試圖返回一個函數中的if-else循環中的數組內的對象。AngularJS和通過函數返回在javascript數組中的對象
基本上,我想返回數組中的第一個item對象,並且getItemDetails將運行並獲取第一個項目,然後如果再次觸發,它將清除該數組並將其他項目對象寫入它。
我有一個叫ItemService服務,包含以下功能:
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);
}
這是控制器:
.controller("itemListingDetailCtrl", function ($scope, itemService, $stateParams, $state)
{
$scope.name = itemService.getItemDetails()[0].name;
$scope.description = itemService.getItemDetails()[0].desc;
})
這裏是包含onSelectItems函數,它接受一個JSON對象作爲手風琴一個參數。
<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>
每當它運行時,我可以在我收到以下錯誤控制檯日誌中看到:
Cannot read property 'name' of undefined
at Object.getItemDetails
如果我刪除的if else循環和簡單地推動該項目的陣列,並返回itemDetails ,它會給我數組中正確的第一項。有任何想法嗎?
在此先感謝。
itemService.getItemDetails()[0] .name;中的'details'在哪裏?因爲服務函數的定義正在尋找getItemDetails中的'details':function(details){} – squiroid