各位,我的网站上有一个表单,我想将其数据存储在 json 文件中。
以下是表单的代码:
<form>
<input ng-model="obj.firstname">
<input ng-model="obj.lastname">
<button ng-click="storedata()">Click here to store data</button>
</form>
我的 Angular 代码如下:
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', {}, {} );
}]);
问题是数据没有被存储。我在这里错过了什么吗? 这是一个 plunkr:http://plnkr.co/edit/gist:3662702
最佳答案
ngResource 是一项 Angular 服务,旨在与 RESTful 服务器端数据源交互(请参阅 ngResource docs)。 Angular js 教程倾向于引用本地 JSON 文件,因为它们是独立的示例,任何人都可以在本地下载和运行,而不需要后端服务器。但您会注意到教程仅从 JSON 文件读取数据,无法更新它们。
如果您希望在客户端保存数据,请查看 LocalStorage ( http://diveintohtml5.info/storage.html )。
如果您尝试保存数据服务器端,则需要设置一些后端服务(通过 NodeJS、PHP、.NET、Ruby、Python 和许多其他框架......)
关于angularjs - 在 Angular 中使用 Resources 将数据存储在 json 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18445423/