var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
// var Answer = require("mongoose");
$scope.circles = [
JSON.parse("{\"x\": 85, \"y\": 20, \"r\":15}"),
/* much more similar entries */
];
);
angular.bootstrap(document.getElementById('body'), ["app"]);
我的问题很简单:
我有一个非常简单的SPA的AngularJS代码。
如何在服务器端(数据库内)保存数组圈,或者更具体地说,如何编写允许我这样做的服务器控制器?
答案 0 :(得分:0)
嗯,在对评论进行讨论的后续工作中,这是编写控制器以将数据发送到服务器的可行方法:
var dbtest = angular.module('dbtest',[]);
var app = angular.module('app', ['dbmodule']);
app.controller('MainCtrl', function($scope) {
// var Answer = require("mongoose");
$scope.circles = [
JSON.parse("{\"x\": 85, \"y\": 20, \"r\":15}"),
/* much more similar entries */
];
);
dbtest.controller("dbtest",function($http) {
var app = this;
//var url=...
app.SaveAnswer = function (newAnswer) {
$http.post(url+"/add", {circle:$scope.circles}).success(function () {
console.log("Success");
})
};
angular.bootstrap(document.getElementById('body'), ["app"]);
//maybe another bootstrap is needed... angular.bootstrap(document.getElementById('dbtest'), ["dbtest"]);
然后对于服务器端的POST方法,server.js文件,我会添加如下内容:
var express = require("express");
var app = express();
var cors = require("cors");
var bodyParser=require("body-parser");
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var Answer = require('../db/db_model');
app.post("/add", function(req, res){
var resp = req.circles;
var answer = new Answer({ans: resp});
answer.save(function(err){
if(err){
console.log("Error");
}
else{
console.log("Saved");}
});
});
//Change this in deployment to port.env or similar
app.listen(3000, function () {
console.log("Port 3000 connected");
});
这些内容是否正确?然后我可以在HTML上使用dbtest控制器,这样当用户点击按钮时矩阵就会保存到数据库中,对吗?