2015-10-16 28 views
0

我正在使用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

您只需要在成功回调中将您的投票分配给$ 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 }}"/>

(?为什么$家长因为NG-重复创建它里面你的控制器范围自己的范围)