When it comes to using $http GET to access a resource on the client side, Chrome may present a CORS error unless you disable web security by running an alternative command. On the other hand, Firefox might incorrectly flag the JSON as not well formed even when it is. These inconsistencies can be frustrating for developers.
If you're looking for a reliable method of storing data on the client side and ensuring its persistence through page refreshes, HTML5 LocalStorage is a solid option. An excellent demonstration of this functionality can be found in the [TodoMVC example](https://github.com/tastejs/todomvc/tree/gh-pages/architecture-examples/angularjs)
The provided code showcases a straightforward approach to saving and retrieving a JSON file from local storage. It includes methods within a Service that enable interaction with the local storage.
INDEX.HTML
<body ng-app = "app">
<div ng-controller="MainCtrl">
<form>
<input placeholder="Enter Name.." ng-model="newContact"/>
<button type="submit" class="btn btn-primary btn-lg"
ng-click="addContact(newContact)">Add
</button>
</form>
<div ng-repeat="contact in contacts track by $index">
{{contact.name}}
</div>
</div>
APP.JS
angular.module('app', ['app.services'] )
.controller('MainCtrl', function ($scope, html5LocalStorage) {
//create variable to hold the JSON
var contacts = $scope.contacts = html5LocalStorage.get();
$scope.addContact = function(contact) {
$scope.contacts.push( {"name":contact} ); //Add new value
html5LocalStorage.put($scope.contacts); //save contacts to local storeage
}
});
SERVICES.JS
angular.module('app.services', [] )
.factory('html5LocalStorage', function () {
var STORAGE_ID = 'localStorageWith_nG_KEY'; //the Local storage Key
return {
//Get the localstorage value
get: function ()
{
return JSON.parse(localStorage.getItem(STORAGE_ID) || '[]');
},
//Set the localstorage Value
put: function (values)
{
localStorage.setItem(STORAGE_ID, JSON.stringify(values));
}
};
});
Alternatively, employing Node and Express to store the JSON file on the server is another viable solution. By utilizing the 'fs-extra' module from the file system, developers can handle interactions with the JSON file effectively.
It would be necessary to establish RESTful API routes for clients to communicate with the server via $http requests for performing CRUD operations.