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.
It would make more sense to save a list of ID's that have been favorited:
When you initialize your controller, you will need to retrieve the list and iterate through your reports: