使用 $scope AngularJS 仅显示数组中的最新值

Value only showing latest in array using $scope AngularJS

所以我试图在选择日历上的日期时显示某些数据(日记条目)(参见图片)

Image of calendar.

Image of result when a date with journal entry is picked.

So when a date is picked and there is a journal entry in the array, it will show on the card at the bottom.

我的问题:

所以我的问题是,当我有多个条目并且我选择了除最后输入的条目之外的任何条目时,它们不会显示。但是当我选择最后一个条目时,它显示完美。

我的代码:

$scope.journalData = {};
for (var i = 0; i < $scope.entryArray.length; i++) {
  if ($scope.entryArray[i].date == $scope.startDate.text) {
    $scope.journalData = $scope.entryArray[i];
    console.log($scope.journalData);
  } else {
    $scope.journalData = {};
  }
}
<div class="card">
   <div class="item item-divider">
    {{journalData.date}}
  </div>
  <div class="item item-text-wrap">
    {{journalData.text}}
  </div>
</div>

$scope.entryArray 是本地存储中的一个数组,它包含所有存储的日志条目,如下所示:

var entry = { date: $scope.startDate.text, text: $scope.formData.journalEntry }

如您所见,我会在日期与所选日期匹配的任何时间进行控制台日志记录。假设我在今天(4 月 20 日)、明天和后天有 3 个条目。这是输出:

{date: "Thu Apr 20 2017", text: "asdfasdf"} {date: "Fri Apr 21 2017", text: "asdfasdfasdf"} {date: "Sat Apr 22 2017", text: "asdfasdfasdf 3"}

并在 3 日更改日期。该卡片在屏幕底部显示数据(就像它应该的那样)。

谁能帮我弄清楚为什么当我控制台日志时它只显示第三个条目并且它存储在正确的变量中?

当您 select 第一次约会时,journalDatafor 循环的第一次迭代中具有正确的值。但在下一次迭代中,由于 if 块中的日期不匹配,它会执行 else 块,因此 journalData 变量再次为空。

如果删除 else 块,它应该可以工作。由于您已经在 for 循环开始之前将 journalData 设置为空白,因此您不需要 else 块。

此外,您可以在找到匹配项后添加 break 来进一步优化您的代码。它会是这样的:

for (var i = 0; i < $scope.entryArray.length; i++) {
  if ($scope.entryArray[i].date == $scope.startDate.text) {
    $scope.journalData = $scope.entryArray[i];
    console.log($scope.journalData);
    break;
  } else {
    $scope.journalData = {};
  }
}

在此,一旦日期匹配,它将打破 for 循环。