如何build立与Angular.js和Node.js槽服务的连接?

我有一个简单的pipe理面板里面有窗体。 我试图通过Angular.js和Node.js连接来更新这个表单的内容。 如果我做到了这一点:我将能够读取表单的数据并在头版上呈现。

这个表单从“/json/form-data.json”读取数据:

[{ "name" : "BigTitleLine1", "content" : "APP TITLE 1" }, { "name" : "BigTitleLine2", "content" : "APP TITLE 2" }]; 

Angular Service从该json文件获取数据:

 ServiceModule.factory('serviceFormData', ['$resource', function ($resource) { return $resource(rootPath("/json/form-data.json"), {}, { query: { method: 'GET', isArray: true } }); }]); 

Angular Controller将数据分配给模型:

 ctrl.controller('formCtrl', ['$scope', '$rootScope', 'serviceFormData', function($scope, $rootScope, serviceFormData) { $scope.model = {}; serviceFormData.query(function(data) { $scope.model.formData = data; }); ]); 

我可以在HTML上显示真实的数据,并保存对模型的更改:

 <form> <div class="form-group" ng-repeat="item in model.formData"> <label>- {{ item.name }}</label> <input class="form-control" ng-model="item.content" required /> <br /> </div> </form> 

我在本地主机上创build了一个Node.JS Express服务器。 它可以读取和写入文件。

 var express = require('express'), fs = require('fs'), app = express(); app.use(express.static(__dirname)); // i can create "localhost:3000/test" page and show this json data over there app.get('/test', function (req, res, next) { res.json({ some: "aq literal" }); }); // i can create "./json/test.json" file and write what i want. fs.writeFile("./json/test.json", "Hey there!", function(err) { if(err) { return console.log(err); } }); var server = app.listen(3000); 

我试图写一个包含submitedangularforms的模型的json文件。 喜欢这个:

 [{ "name" : "BigTitleLine1", "content" : "I've edited this json from my angular form which is on the client side." }, { "name" : "BigTitleLine2", "content" : "APP TITLE 2" }]; 

如何build立Angular.js和Node.js之间的连接?

您应该更改工厂以处理新的对Node的调用以更新文件(或创build新的工厂):

 ServiceModule.factory('serviceFormData', ['$resource', function ($resource) { return $resource('/update', {}, { update: { method: 'PUT' } }); }]); 

那么你应该用更新方法更新Angular控制器:

 var json = new serviceFormData.update($scope.item); json.$update(function (response) { $scope.success = true; }, function (response) { $scope.error = response; }); 

最后,你应该用一个新的路由来处理Node:

 var bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.put('/update', function (req, res) { var arr = [] for (var index in req.body){ arr.push(req.body[index]) } var jsonData = JSON.stringify(arr, null, 2); fs.writeFile("./json/test.json", jsonData, function(err) { if(err) { return console.log(err); } res.json({ success: true }); }); }); 

我没有testing,但这是要走的路。