Sam Alexander
Sam Alexander

Reputation: 491

Return Statement In Angular not working for an object

Pretty basic stuff... Seems like it should be working but does not

Both console logs here spit out the correct information.

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

But later in the file Calling it turns undefined

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

Any help would be much appriciated. I have no idea why this doesn't work

Upvotes: 2

Views: 1480

Answers (1)

Manu Obre
Manu Obre

Reputation: 2304

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

The return clause that you have in here, is for the angular.forEach function, not for the getCurrentAttachment .

You could do the following, using the .filter function from the Array ptototype.

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

  });
  return filteredArray ;
};

Upvotes: 5

Related Questions