2015-11-07 81 views
2

我正在嘗試製作一個角度指令,該指令需要帶有問題和若干答案的對象。然後,它應該將答案顯示爲單選按鈕,以便用戶可以選擇一個投票,然後將其發送回服務器。角度指令中的單選按鈕不起作用

在我的版本上,ng-model/scope變量沒有更新。

<div> 
    <h3> {{poll.question}}</h3> 
    <div class="list-group"> 
<form> 
    <label ng-repeat="option in poll.options" for="{{option.optionName}}">{{option.optionName}} 
    <input type="radio" id="{{option.optionName}}" ng-model="selectedOption" ng-value="option.optionName" name="option"/> 
    </label> 
</form> 
</div> 
    <button ng-class="btn" ng-click="sendOption()">Send Vote</button> 
    <p>the option you selected is: {{selectedOption}}</p> 

.directive('voter', function() { 
return { 
    templateUrl: 'app/voter/voter.html', 
    restrict: 'EA', 
    scope:{ 
    poll:'=' 
    }, 
    controller:function($scope,$http,Auth){ 
     $scope.selectedOption = 'no option selected'; 
     $scope.sendOption = function(){console.log($scope.selectedOption);}; 


    }, 
    link: function (scope, element, attrs) { 
    } 
}; 
}) 

它顯示的選項投票答案,但$ scope.selectedOption不會改變?我之前沒有在Angular上使用單選按鈕,所以可能錯過了一些明顯的東西。

感謝任何幫助

回答

1

的問題是,你正在使用ng-modelng-repeat。當您使用ng-repeat中繼器中的每個項目都創建了自己的作用域。當你點擊一個單選按鈕時,你在這個新創建的範圍上更新selectedOption ...不是指令上的範圍。這就是爲什麼你的段落中的綁定沒有被更新。

,可以快速使用對象(vote)舉行表決結果解決這個問題:

<input type="radio" id="{{option.optionName}}" ng-model="vote.result" ng-value="option.optionName" /> 
... 
<p>the option you selected is: {{vote.result}}</p> 
... 
controller:function($scope) { 
    $scope.vote = {result: null} 
    $scope.sendOption = function(){console.log($scope.vote.result);}; 
} 

看到這個plunker

編輯:我修復了一個小錯誤。它通過未定義的方式訪問投票。我的答案現在用一個點代替方括號。 Plunker也已更新。

欲瞭解更多信息,請參閱

1

您可以使用此方法來跟蹤selectedOption的假設你只有一個selectedOption在同一時間。它初始化表單上的selectedOption變量,然後每次單擊一個輸入時,它會通知父窗體將該變量更改爲選定的索引。

<form ng-init="selectedOption=0"> 
    <label ng-repeat="option in poll.options" for="{{option.optionName}}">{{option.optionName}} 
    <input type="radio" id="{{option.optionName}}" ng-value="option.optionName" ng-click="$parent.selectedOption=$index" name="option"/> 
    </label> 
</form>