I am storing objects in a `$localStorage` array for persistence. I have a check function to see if an object is already present in the array before adding or removing it (using `splice` if present, and `push` if not).
However, after refreshing my page, the data retrieved from `$localStorage` seems different than before, even though it appears identical upon inspection. Therefore, my check function no longer works properly.
The structure of the objects being pushed:
{
"createdAt": "2015-04-24T10:21:21.649Z",
"difficulty": "Hard",
"exerciseDescription": "Lie on your back on a bench and take hold",
"exerciseID": "3101",
"exerciseName": "Bench Press",
"images": [8679, 8680, 8682],
"tags": ["Barbell", "Horizontal Flexion", "Extension", "Strength", "Chest", "Triceps", "Shoulder", "Elbow, Wrist & Hand"],
"updatedAt": "2015-09-09T20:14:59.681Z",
"words": ["bench", "press", "chest"],
"objectID": "ak6t7ukQdY",
"_highlightResult": {
"exerciseName": {
"value": "Bench Press",
"matchLevel": "none",
"matchedWords": []
}
}
}
Check for object presence (toggle add/remove)
$scope.addExerciseToProgramme = function(exercise) {
if (!$localStorage.Programme) {
$localStorage.Programme = [];
}
var index = $localStorage.Programme.indexOf(exercise);
if (index > -1) {
$localStorage.Programme.splice(index, 1);
} else {
$localStorage.Programme.push(exercise);
}
}
Function to watch/load $localStorage
$scope.$watch(function() {
return $localStorage.Programme
}, function(programme) {
$scope.programme = programme;
});
ng-class to check if exercise is in programme
<i class="exercise-add-indicator ion-ios-checkmark-outline" ng-class="{'orange': programme.indexOf(exercise) > -1}"></i>
Issues
There are two issues with the current setup:
After refresh, the `ng-class` does not correctly apply the class based on the content of `$scope.programme`.
The `addExerciseToProgramme` function does not respect the `indexOf` check and adds the exercise object to the array regardless!