I've been trying to implement localstorage using ngStorage in this AngularJS app I've been working on. Debugging I keep finding data type issues and errors even though everything appears fixed.
This is the plunk: http://plnkr.co/edit/IpPDb4
// app.js
var app = angular.module('noteMate', ['ngRoute']);
app.controller('MainCtrl', function($scope, Notes) {
$scope.notes = Notes.entries;
$scope.tempNote = {};
var index;
$scope.save = function() {
Notes.save($scope.tempNote);
$scope.clear();
};
$scope.del = function(idx) {
Notes.del(idx);
};
$scope.edit = function(idx) {
$scope.tempNote = angular.copy($scope.notes[idx]);
index = idx;
};
$scope.clear = function() {
$scope.tempNote = {};
};
$scope.saveEdit = function() {
$scope.notes[index] = $scope.tempNote;
};
$scope.mouse = false;
});
app.service('Notes', function(){
this.saved = $localStorage.getItem('notes');
this.entries = ($localStorage.getItem('notes')!==null) ? JSON.parse(this.saved) :
[{title: "Hey", desc: "This is a sample note. Add your own note by clicking the button below. :)"}];
$localStorage.setItem('notes',JSON.stringify(this.entries));
this.save = function(entry) {
this.entries.push(entry);
$localStorage.setItem('notes',JSON.stringify(this.entries));
};
this.del = function(idx) {
this.entries.splice(idx, 1);
$localStorage.setItem('notes',JSON.stringify(this.entries));
};
});
Any solutions for the problem and explanation for the issue?
1) put link
<script type="text/javascript" src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
2) need ngStorage
to inject
var app = angular.module('noteMate', ['ngRoute','ngStorage']);
check example Here
When working with a $localStorage
service, you first have to define that yourself somewhere, or get it from elsewhere (ie. module).
I would recommend you to look at this one: https://github.com/gsklee/ngStorage
Then restructure your code to look like this:
app.service('Notes', function($localStorage){
this.$storage = $localStorage;
this.saved = $localStorage.notes;
this.entries = ($localStorage.notes!==null) ? JSON.parse(this.saved) :
[{title: "Hey", desc: "This is a sample note. Add your own note by clicking the button below. :)"}];
});
You did have a few minor issues with that plunkr (tether not linked, wrong sequence of loading libraries (bootstrap/jQuery)), but the main issue was the use of the localStorage service.
Have a look at the corrections in my plunker: http://plnkr.co/edit/K6EKlv1LvJOzKTQo154O?p=preview
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.