One of the functionalities I want to implement is displaying a list of items (subject names) that are stored in a LocalStorage element. The code snippet in my view is structured as follows:
<div class="list">
<a class="item" href="#" ng-repeat="subject in subjects">
{{subject.name}}
</a>
</div>
This is how my controller is set up:
.controller('SubjectCtrl', function ( $scope ) {
$scope.subjects = store.get('subjects');
$scope.submit = function() {
if (store.get('subjects') != null) {
var existing = store.get('subjects')
var subject = [ { name: $scope.form.name, weighting: $scope.form.weighting, grades: [] } ]
subject.add(existing)
store.set('subjects', subject)
}
else {
var subject = [ { name: $scope.form.name, weighting: $scope.form.weighting, grades: [] } ]
store.set('subjects', subject)
}
};
})
The $scope.subjects variable fetches data from LocalStorage using Store.js (https://github.com/marcuswestin/store.js, a Plugin that simplifies LocalStorage access) and passes it to the view.
Upon submitting a form to add a new subject, the following code block executes. The form comprises 'name' and 'weighting' inputs. If there are existing subjects in the 'subjects' LocalStorage object, the new subject gets appended to the array, updating the LocalStorage. If not, a new LocalStorage object named 'subjects' is created, and the new subject is added.
Despite functioning correctly, I face an issue where Angular fails to update the view when a new subject is added to the array in LocalStorage, necessitating a manual page reload to reflect the changes.
After some investigation, I discovered this might be due to updating the LocalStorage object outside of AngularJS’s scope. As a novice in Angular, I seek guidance on the best approach to alert Angular about object modifications promptly.
Any assistance would be highly appreciated!
-- UPDATE --
I've transitioned from store.js (incompatible with Angular) to ngStorage (https://github.com/gsklee/ngStorage). To potentially aid others, here's my revised controller code employing ngStorage:
.controller('SubjectCtrl', function ( $scope, $localStorage ) {
$scope.$localStorage = $localStorage.$default({
subjects: []
});
$scope.subjects = $localStorage.subjects;
$scope.submit = function() {
$localStorage.subjects.push({ name: $scope.form.name, weighting: $scope.form.weighting, grades: [] });
};
})