Skip to content

Instantly share code, notes, and snippets.

@kauffmanes
Created June 18, 2017 14:37
Show Gist options
  • Save kauffmanes/2f790732c0e845ea6047bf60fecb6002 to your computer and use it in GitHub Desktop.
Save kauffmanes/2f790732c0e845ea6047bf60fecb6002 to your computer and use it in GitHub Desktop.
Final full app.js file
angular.module('app', [])
.controller('MainController', ['$scope', function ($scope) {
var fetchAll = function () {
var finds = [];
if (localStorage.length === 0) {
return [];
}
for (var i=0;i<localStorage.length;i++) {
try {
finds.push(JSON.parse(localStorage.getItem(localStorage.key(i))));
} catch (err) {
console.log(err);
}
}
return finds;
};
$scope.formData = {};
//Parses and saves to localStorage
$scope.save = function () {
var stringCopy = '';
//lc only accepts strings
//allows us to reference this lc record later
$scope.formData.lcKey = Date.now().toString();
try {
stringCopy = JSON.stringify($scope.formData);
} catch (err) {
//error handling for bad form submission
console.debug(err);
return;
}
localStorage[$scope.formData.lcKey] = stringCopy;
};
//Once connection is detected, submit to server
$scope.sync = function () {
var records = fetchAll();
//if connection exists
if (navigator && navigator.onLine && records.length) {
records.forEach(function (find, idx) {
//make service call for each record
$http({
url: '/api/finds',
method: 'POST',
data: find
}).then(function (res) {
//JS date sometime display differently, so toString keeps it more persistent
localStorage.removeItem(find.lcKey.toString());
records.splice(idx); //remove from records array
}, function (err) {
//error handling - service call failures
});
});
} else {
//error handling - alert user that a connection could not be established
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment