runtimeZero
runtimeZero

Reputation: 28076

Using Resources to store data in json file in Angular

Folks I have a form on my website who's data I want to store in a json file.

Here is the code for the form:

 <form>
    <input ng-model="obj.firstname">
    <input ng-model="obj.lastname">     
    <button ng-click="storedata()">Click here to store data</button>        
</form>

My Angular code is as below:

var myApp = angular.module('app', ['ui.bootstrap.dialog','ngResource']);

myApp.controller('TestCtrl', function($scope,$dialog,TestResource) { 
 $scope.obj = {};
 $scope.obj.firstname = "Mahatma";
 $scope.obj.lastname = "Gandhi";

 $scope.storedata = function() {
    console.log("Storing Data now");
    TestResource.save($scope.obj);
    console.log("Data should have been stored");
 }
});


myApp.factory('TestResource', ['$resource', function($resource) {
  return $resource('test.json', {}, {} );
}]);

The problem is that the data does not get stored. Am I missing something here ? Here is a plunkr : http://plnkr.co/edit/gist:3662702

Upvotes: 2

Views: 17128

Answers (1)

Mike Pugh
Mike Pugh

Reputation: 6787

ngResource is an Angular service designed to interact with RESTful server side data sources (see ngResource docs). The angular js tutorials tend to reference local JSON files since they're meant to be stand-alone examples which anyone can download and run locally without the need for a back-end server. But you'll notice the tutorials only read data from the JSON files, they cannot update them.

If you're looking to save data client side, check out LocalStorage (http://diveintohtml5.info/storage.html).

If you're trying to save the data server side, you'll need to setup some back end service (via NodeJS, PHP, .NET, Ruby, Python, and many other frameworks..)

Upvotes: 3

Related Questions