I am trying to learn angular and I have run into a problem. I have a form that submits an Item Name, Price, and Image to MongoDB. In my Node route I am using res.json as the response. While using the jQuery POST method I can stay on the page and return the data to the console or a variable or whatever. When I changed to the angular POST method I am actually going to a new page that contains the JSON response. This of course is not what I want. I want to update the database, GET the new data, and update the model without ever leaving the page.
This is my node route.
router.post('/items/add', function(req, res){
// handle image upload
fs.readFile(req.files.image.path, function (err, data) {
var imageName = req.files.image.name
/// If there's an error
if(!imageName){
console.log("There was an error")
res.redirect("/");
res.end();
} else {
var newPath = '/uploads/' + imageName;
/// write file to uploads/fullsize folder
fs.writeFile(newPath, data, function (err) {
});
}
});
// save info to database
var newItem = new Item({
name : req.param('Name'),
price : req.param('Price'),
image : req.files.image.name
});
newItem.save(function(err){
if(err){
console.log(err);
} else{
Item.find(function(err, items){
if (err){
return console.log(err);
} else{
res.json({
items : items
});
}
});
}
});
});
This is my angular code:
var allItems = angular.module('allItems', []);
allItems.controller('allItemsCtrl', function ($scope, $http) {
$scope.updateItems = function(){
$http.get('/allItems').success(function(data){
$scope.theitems = data.allItems;
});
};
// The culprit
$scope.postItems = function(){
$scope.formData = {};
$http.post('/items/add', formData).success(function(data){
$scope.theitems = data.allItems;
});
};
$scope.updateItems();
});
The data is POSTing correctly, however I want it to act like an AJAX post and not leave the page. How do I accomplish this?
$http.post()request not act like a AJAX request ! How are you invoking$scope.postItems()?