我正在使用yeoman的angular-fullstack生成器制作一个小型的民意调查应用程序。我为民意调查设置了一些虚拟数据。当用户点击投票时,他们会被路由到一个视图页面,在那里他们可以根据为问题设置的答案输入他们的选择。
目前,当用户选择一个选项并按下提交时,更改会在客户端更新,但我无法知道要为数据库POST请求放置什么。
以下是view
视图:
<div class="container">
<h3>{{poll.title}}</h3>
<form ng-submit="submitForm()">
<div ng-repeat="answer in poll.answers">
<label><input type="radio" name="option" ng-model="radioData.index" value="{{$index}}"/>
{{ answer.value }} - {{ answer.votes }} Votes
</label>
</div>
<button class="btn btn-success" type="submit">Vote!</button>
</form>
</div>
这是它的控制器:
'use strict';
angular.module('angFullstackCssApp')
.controller('ViewCtrl', function ($scope, $routeParams, $http) {
$http.get('/api/polls/' + $routeParams._id).success(function (poll) {
console.log(poll);
$scope.poll = poll;
$scope.radioData = {
index: 0
};
$scope.viewPoll = true;
$scope.alreadyVoted = false;
$scope.submitForm = function () {
$scope.alreadyVoted = true;
console.log($scope.radioData.index);
$scope.poll.answers[$scope.radioData.index].votes += 1;
// Change database entry here
};
});
});
这是我的民意调查架构:
var PollSchema = new Schema({
creator: String,
title: String,
answers: [{
value: String,
votes: Number
}]
});
所以我的问题是: -
如何编写合适的POST请求以增加对答案的投票?
在我这样做的GET请求中编写代码是否正确?感觉必须有一个更合适的方法,特别是由于我在其中调用另一个请求。
答案 0 :(得分:0)
您只需要在成功回调中将您的投票分配给$ scope.poll。其他变量可以在回调之外设置。
对我来说,为你的答案分配一个id是有意义的,那么你可以告诉你api什么答案ID应该得到额外的投票,然后传递给你。
$scope.submitForm = function() {
$http.post('/api/addVote/',
{ answerId: $scope.votedAnswerId }
).success(function () {
alert("success");
}).catch(function () {
alert("some error occurred");
});
};
您的输入变为:
<input type="radio" name="option" ng-model="$parent.votedAnswerId" value="{{ answer.id }}"/>
(为什么是$ parent?因为ng-repeat在你的控制器范围内创建它自己的范围。)