我有一个简单的管理面板,里面有表单。我正在尝试通过 Angular.js 和 Node.js 连接更新此表单的内容。如果我做到了这一点:我将能够读取表单的数据并在首页上呈现。
此表单从以下位置读取数据:“/json/form-data.json”:
[{
"name" : "BigTitleLine1",
"content" : "APP TITLE 1"
}, {
"name" : "BigTitleLine2",
"content" : "APP TITLE 2"
}];
Angular 服务从该 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>
我在本地主机上创建了一个 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);
我正在尝试编写一个 json 文件,其中包含提交的 Angular 表单的模型。如下所示:
[{
"name" : "BigTitleLine1",
"content" : "I've edited this json from my angular form which is on the client side."
}, {
"name" : "BigTitleLine2",
"content" : "APP TITLE 2"
}];
如何在 Angular.js 和 Node.js 之间建立这种连接?
最佳答案
您应该更改工厂来处理对 Node 的新调用以更新文件(或创建新工厂):
ServiceModule.factory('serviceFormData', ['$resource', function ($resource) {
return $resource('/update', {}, {
update: {
method: 'PUT'
}
});
}]);
然后你应该使用 update 方法更新 Angular Controller :
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 });
});
});
我没有测试过,但这是可行的方法。
关于javascript - 如何通过服务与 Angular.js 和 Node.js 建立连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32268250/