How to store 'Favorites' items in Local Storage from an ng-repeat list (AngularJS)?

470 views Asked by At

I'm trying to make a list with AngularJS, which shows "Reports" that can be saved as "Favorite". Let's say I have my reports as JSON format:

var reports = [
   {
     "ID":1,
     "Title":"Report 1",
     "color":"blue",
     "Favorite": false
   },
   {
     "ID":2,
     "Title":"Report 2",
     "color":"red",
     "Favorite": false
   }
   ...
];
$scope.reports = reports;

Notice there's a field called "Favorite" which is always FALSE. In my HTML I put two different buttons: the "favorite" button is shown only if Favorite is set to FALSE, and the "Unfavorite" is shown when it is set to TRUE. I added a function that changes Favorite to TRUE when you click the button and Unfavorite the report when clicked again:

<div class="card" dir-paginate="report in reports | filter:filterByRadio | itemsPerPage:4">
  <h3>{{report.Title}}</h3>
  <p>Color: {{report.color}}</p>
  <!-- These are the buttons to Favorite or Unfavorite -->
  <a href="#" title="Add to Favorite" ng-if="report.Favorite == false" ng-click="favoriteReport(report)">
     <i class="material-icons">favorite_border</i> Favorite
  </a>
  <a href="#" title="Unfavorite" ng-if="report.Favorite == true" ng-click="unfavoriteReport(report)">
     <i class="material-icons">favorite</i> Favorited
  </a>
</div>

The function:

$scope.favoriteReport = function(report) {
  report.Favorite = true;
}
$scope.unfavoriteReport = function(report) {
  if(confirm('Are you sure you want to Unfavorite this Report?')) {
    report.Favorite = false;
  }
}

As I think my code is a little too long, I've made a Plunker.

So my question is if it is possible to maintain "favorite" as TRUE in the Local Storage. I downloaded ngStorage but I really don't know how to make it work. If anybody has a better approachment on how to resolve this, any idea is well appreciated.

1

There are 1 answers

0
Pop-A-Stash On

It would make more sense to save a list of ID's that have been favorited:

function favorite(report) {
  report.Favorite = true;
  if($scope.favoriteReports.indexOf(report.ID) === -1) {
    $scope.favoriteReports.push(report.ID);
    $localStorage.favoriteReports = $scope.favoriteReports;
  }
}

function unfavorite(report) {
  var reportIndex = $scope.favoriteReports.indexOf(report.ID);
  if( reportIndex > -1) {
    report.Favorite = false;
    $scope.favoriteReports.splice(reportIndex, 1);
    $localStorage.favoriteReports = $scope.favoriteReports;
  }
}

When you initialize your controller, you will need to retrieve the list and iterate through your reports:

function init() {
  $scope.favoriteReports = $localStorage.favoriteReports || [];
  $scope.reports.each(function(report) {
      if($scope.favoriteReports.indexOf(report.ID) > -1) {
        report.Favorite = true;
      }
  });
}