【发布时间】:2013-11-22 13:58:37
【问题描述】:
我正在使用 AngularJS、Node、Express 和 MongoDB 创建一个 CRUD 待办事项应用程序。除了更新部分,我已经弄清楚了所有部分。我不确定如何实现它或代码可能是什么样子。特别是 AngularJS 的东西(快速路由还不错)。如果我可以通过 ID 更新,我会喜欢它。希望得到一些意见。
function mainController($scope, $http) {
$scope.formData = {};
// when landing on the page, get all todos and show them
$http.get('/api/todos')
.success(function(data) {
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
// when submitting the add form, send the text to the node API
$scope.createTodo = function() {
$http.post('/api/todos', $scope.formData)
.success(function(data) {
$('input').val('');
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
// delete a todo after checking it
$scope.deleteTodo = function(id) {
$http.delete('/api/todos/' + id)
.success(function(data) {
$scope.todos = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
这里是路线以防万一。
app.get('/api/todos', function(req, res) {
// use mongoose to get all todos in the database
Todo.find(function(err, todos) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err)
res.json(todos); // return all todos in JSON format
});
});
// create todo and send back all todos after creation
app.post('/api/todos', function(req, res) {
// create a todo, information comes from AJAX request from Angular
Todo.create({
text : req.body.text,
done : false
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
});
// delete a todo
app.delete('/api/todos/:todo_id', function(req, res) {
Todo.remove({
_id : req.params.todo_id
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
});
// application -------------------------------------------------------------
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
};
【问题讨论】:
-
只需将
$http.put与适当的url(/api/todos/' + id形式)一起使用,并在data参数中指定您的更新。 -
这样吗? $http.put(/api/todos/' + id) .success(function(data) { $scope.todos = data; })?
-
差不多:
$http.put('url', data : {property1:newValue1, ... , propertyN:newValueN}).success(function(data){...}).error(function(err){...})
标签: javascript node.js angularjs express