Search code examples
javascriptangularjsionic-frameworkangularjs-scope

Value only showing latest in array using $scope AngularJS


So I am trying to show certain data (journal entries) when a date on a calendar is chosen (See images)

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.

My issue:

So my issue is that when I have multiple entries and I pick any of the entries except the last entered, they do not show up. But when I pick the last entry, it shows perfectly.

My Code:

$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 is a array from local storage that holds all journal entries stored like so:

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

As you can see I console log anytime a date matches the selected date. Let's say I have 3 entries on today(April 20), tomorrow and the next day. Here is the output:

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

And on the 3rd date change. The card shows the data at the bottom of the screen (like it should).

Can anyone help me figure out why it only shows the 3rd entry when I console log and it is stored in the correct variable?


Solution

  • When you select the first date, the journalData has the correct value in the first iteration of the forloop. But in the next iteration, as the date does not match in the if block, it executes else block and so the journalData variable is empty again.

    If you remove the else block, it should work. As you already set journalData to blank before the start of the for loop, you do not need the else block.

    Also, you can optimize your code a bit further by adding a break once you find the match. It would be something like:

    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 = {};
      }
    }
    

    In this, it will break the for loop once the date matches.