表单数据未发布到数据库

时间:2018-01-29 08:37:26

标签: angularjs mean-stack

我在捕获表单中的数据并将其发送到服务器时遇到了一些问题。我测试了结束点并且工作正常,如果我将虚拟值放在角度和提交中似乎工作正常但是当我尝试从我的表单中获取值时,我回来的都是空白对象。

{
    "_id": "5a6ed91d37fcd13024593b78",
    "__v": 0
}

快速路线

router.post('/booking/addReservation', function (req, res, next) {
 Booking.create(req.body, function (err, post) {
    if(err) return next(err);
    res.json(post);
  });
});

Angular Factory

app.factory('postReservationOne', function ($resource) {
return $resource('http://localhost:5016/api/booking/addReservation')
});

控制器

app.controller('addReservationOne', function ($scope, postReservationOne) {

$scope.reservation = {};
$scope.newReservation = function () {
    var reservationOne = new postReservationOne($scope.reservation);
    reservationOne.$save();
}
});

表格

 <input type="text" class="form-control" placeholder="First Name" 
        name="firstName" ng-required="true"
        ng-model="reservation.firstName">
 <input type="text" class="form-control" placeholder="Last Name"
        name="lastName" ng-required="true"
        ng-model="reservation.lastName">
 <button type="submit" class="btn btn-primary"
         ng-controller="addReservationOne"
         ng-click="newReservation()">Submit</button>

2 个答案:

答案 0 :(得分:1)

我的角度有点生疏,但我相信这是因为你在这里创造了一个新的$scope。在您的代码示例中,我看到您的ng-controller位于按钮上。

您的表单元素正在修改外部$scope.reservation值,但保留&#34;内部&#34; $scope(按钮)未触动过。我的猜测是,如果你在debugger函数中抛出console.lognewReservation,你会发现$scope.reservation为空。

尝试使用包含addReservationOne控制器的标记来包装表单元素,而不是按钮。

<form ng-controller="addReservationOne">
  <input ng-model="reservation.firstName">
  <!-- etc -->
</form>

答案 1 :(得分:1)

控制器应封装表格:

<div ng-controller="addReservationOne">
  <form name="form1">
     <input type="text" class="form-control" placeholder="First Name" 
            name="firstName" ng-required="true"
            ng-model="reservation.firstName">
     <input type="text" class="form-control" placeholder="Last Name"
            name="lastName" ng-required="true"
            ng-model="reservation.lastName">
     <button type="submit" class="btn btn-primary"
             ̶n̶g̶-̶c̶o̶n̶t̶r̶o̶l̶l̶e̶r̶=̶"̶a̶d̶d̶R̶e̶s̶e̶r̶v̶a̶t̶i̶o̶n̶O̶n̶e̶"̶
             ng-click="newReservation()">Submit</button>
  </form>
</div>

控制器也应该使用工厂来创建reservation对象:

app.controller('addReservationOne', function ($scope, postReservationOne) {

    $scope.reservation = ̶{̶}̶;̶ new postReservationOne();
    $scope.newReservation = function () {
        ̶v̶a̶r̶ ̶r̶e̶s̶e̶r̶v̶a̶t̶i̶o̶n̶O̶n̶e̶ ̶=̶ ̶n̶e̶w̶ ̶p̶o̶s̶t̶R̶e̶s̶e̶r̶v̶a̶t̶i̶o̶n̶O̶n̶e̶(̶$̶s̶c̶o̶p̶e̶.̶r̶e̶s̶e̶r̶v̶a̶t̶i̶o̶n̶)̶;̶
        ̶r̶e̶s̶e̶r̶v̶a̶t̶i̶o̶n̶O̶n̶e̶.̶$̶s̶a̶v̶e̶(̶)̶;̶
        //Save the Resource object
        reservation.$save();
    }
});

有关详细信息,请参阅AngularJS ngResource $resource API Reference