Created
March 17, 2015 13:54
-
-
Save kyleschmolze/2d0fd6eac4e8bc65cf2a to your computer and use it in GitHub Desktop.
Simple Angular Database - JSON in LocalStorage as a service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
This dead-simple service just returns a javascript object called "Db", | |
which comes with two functions built in: save() and clear(). | |
Save attributes directly onto the object, then call Db.save(), and it | |
will be written into localstorage. | |
Sample usage: | |
angular.module("my_app").controller "HomeCtrl", (Db) -> | |
$scope.user = Db.user || {}; | |
$scope.updateUser = -> | |
Db.user = $scope.user | |
Db.user.updated_at = new Date() | |
Db.save() | |
$scope.logout = -> | |
Db.clear() | |
caveat: Since functions can't be JSON-stringified, don't store functions | |
inside the Db object. | |
### | |
angular.module("my_app").service "Db", -> | |
db = window.localStorage.getItem "my_app_database" | |
db = if db? then JSON.parse(db) else {} | |
# Set any default settings here, if needed | |
db.defaultKey or= "defaultValue" | |
db.save = -> | |
window.localStorage.setItem "my_app_database", JSON.stringify(db) | |
db.clear = -> | |
for key, val of db | |
delete db[key] if db.hasOwnProperty(key) and key isnt 'save' and key isnt 'clear' | |
db.save() | |
return db |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should really wrap in try/catch block because of possible exceptions: https://gist.github.com/drGrove/599fd38f509a439825b2