2015-05-16 73 views
0

我有麻煩試圖返回一個函數中的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 ,它會給我數組中正確的第一項。有任何想法嗎?

在此先感謝。

+0

itemService.getItemDetails()[0] .name;中的'details'在哪裏?因爲服務函數的定義正在尋找getItemDetails中的'details':function(details){} – squiroid

回答

1

首先重要的是,的if-else不是一個循環,但條件語句,循環的例子是。您可以在MDN上閱讀關於control flowloops的更多信息。

您得到的錯誤是因爲您期望details作爲參數傳遞到getItemDetails時始終被定義。您正在訪問此行中的name屬性:console.log (itemDetails[0].name);。但是在控制器代碼中,您無需任何參數即可調用itemService.getItemDetails(),因此detailsundefined,並且引發TypeError

如果你想這個工作,你應該傳遞一個有效的對象到getItemDetails。請繼續關注設計,getItemDetails的作用對我來說還不清楚。您只需將details對象包裝到Array中,您確實不需要服務就可以做到這一點。

此外在getItemDetails函數中,您有無法訪問的代碼。 return之後立即執行的console.log不會被執行。你應該刪除它。

+0

我同意,服務通常用於持久化和共享控制器之間的數據。此外,通常將業務邏輯保存在服務內部的控制器和數據邏輯中。 – LordTribual