我在捕获表单中的数据并将其发送到服务器时遇到一些问题。我测试了终点,效果很好,如果我将虚拟值放在角度中并提交,这似乎工作正常,但是当我尝试从我的表单中获取值时,我得到的只是空白对象。
{
"_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);
});
});
角工厂
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>
控制器应封装以下形式:
<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 参考
我对我的角度有点生疏,但我相信这是因为您在这里创建了一个新$scope
。在您的代码示例中,我看到您的ng-controller
位于按钮上。
表单元素正在修改外部$scope.reservation
值,但保留"内部"$scope
(按钮(不变。我的猜测是,如果你在newReservation
函数中抛出一个debugger
或console.log
,你会看到$scope.reservation
是空的。
尝试使用包含addReservationOne
控制器而不是按钮的标记来包装表单元素。
<form ng-controller="addReservationOne">
<input ng-model="reservation.firstName">
<!-- etc -->
</form>