【发布时间】:2014-07-29 01:16:43
【问题描述】:
我正在尝试理解 MEAN 堆栈中的通信。
我编写了以下代码,使用 yeoman 全栈生成器来搭建应用程序:
- 猫鼬模式
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var StuffSchema = new Schema({
name: String,
});
mongoose.model('Stuff', StuffSchema);
- 保存在 mongodb 上的代码
'use strict';
var mongoose = require('mongoose'),
Stuff = mongoose.model('Stuff');
exports.create = function(req, res, next){
var newStuff = new Stuff(req.body);
newStuff.save(function(err){
if (err) return res.json(400, err);
})
res.send(newStuff);
}
- 节点路由
'use strict'
var stuff = require('./controllers/stuff'),
module.exports = function(app) {
app.route('/api/stuffs')
.post(stuff.create);
}
- 角度服务
'use strict';
angular.module('ngStuff').factory('Stuff', function ($resource) {
return $resource('/api/stuffs/');
});
- 角度控制器
'use strict';
angular.module('ngStuff').controller('StuffCtrl', function($scope, $location, Stuff){
$scope.stuff = {};
$scope.add = function(){
var stuff = new Stuff({name: $scope.stuff.name});
stuff.$save(function(response){
$location.path('#/');
});
$scope.stuff.name = "";
}
});
现在,我可以在 mongodb 上保存文档,但位置没有改变。 这是连接在一起的正确方法吗?有没有更好的方法来做到这一点? 我应该在角度服务而不是角度控制器中编写保存功能吗?
【问题讨论】:
-
你能添加你的角度路线吗...
标签: node.js angularjs express mongoose mean-stack