2016-12-30 87 views
1

漂亮的基本東西...似乎它應該工作,但沒有Return Statement在Angualr沒有爲一個對象工作

這兩個控制檯日誌吐出正確的信息。

$scope.getCurrentAttachment = function() { 
    angular.forEach(attachments, function(attachment) { 
    console.log(attachment); 
    if(attachment.active) { 
     console.log(attachment); 
     return attachment; 
    } 
    }); 
}; 

但後來該文件調用它輪流不確定

$scope.save = function() { 
    console.log($scope.getCurrentAttachment()); 
    var data = [$scope.labels.selected, $scope.getCurrentAttachment()]; 
    console.log(data); 
    $uibModalInstance.close(data); 
}; 

任何幫助將大大appriciated。我不知道爲什麼這不起作用

+0

什麼是「附件」?它沒有被傳入$ scope.getCurrentAttachment作爲參數。範圍變量,全局變量,...? – jbrown

+0

什麼應該工作?什麼是'undefined'? '$ scope.getCurrentAttachment'函數或'attachment'變量? [問]使用[mcve] – TheSharpieOne

+0

返回的$ scope.getCurrentAttachment()未定義。 另外附件是一個填充的對象數組,將成功顯示在日誌中 –

回答

4
$scope.getCurrentAttachment = function() { 
    angular.forEach(attachments, function(attachment) { 
    console.log(attachment); 
    if(attachment.active) { 
     console.log(attachment); 
     return attachment; 
    } 
    }); 
}; 

您在這裏擁有的return條款,是針對angular.forEach功能,而不是爲getCurrentAttachment。

您可以使用Array ptototype的.filter函數執行以下操作。

$scope.getCurrentAttachment = function() { 
    var filteredArray = [] 
    filteredArray = attachments.filter(function(attachment) { 
    console.log(attachment); 
    return attachment.active; 

    }); 
    return filteredArray ; 
}; 
+1

完美,謝謝。我最終修改了一些代碼。我只是設置一個範圍變量,而不是從函數返回。無論您的信息是非常有用的。非常感謝!當我允許時,我會接受你的回答 –

相關問題