Return Angular 中的语句不适用于某个对象

Return Statement In Angular not working for an object

非常基本的东西...看起来应该可以,但没有

这里的两个控制台日志都输出了正确的信息。

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

但是后面在文件中调用它变成了undefined

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

非常感谢任何帮助。我不知道为什么这不起作用

$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 ;
};