2015-10-16 29 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-重複創建它裏面你的控制器範圍自己的範圍)