angularjs - 在 Angular 中使用 Resources 将数据存储在 json 文件中

标签 angularjs

各位,我的网站上有一个表单,我想将其数据存储在 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/

相关文章:

angularjs - 如何使用一个文件中定义的所有 View 创建 AngularJS 应用程序?

javascript - 如何设置默认单选按钮的值?

javascript - AngularJs 选择添加选项

angularjs - 如何隐藏或禁用按钮?

javascript - AngularJS - HTML 数据绑定(bind) UI 问题

angularjs - 指令隔离范围与 attrs.$observe

javascript - 为什么我的 $q deferred 没有在 Angular 单元测试中解决?

javascript - Angular 指令获取 "Synchronous XMLHttpRequest on the main thread is deprecated"

javascript - 如何在不缩小的情况下构建 Yeoman Angular-FullStack

javascript - 错误: Not a function - Angular Service