如何使用AngularJS获取最后选择的单选按钮

时间:2016-07-27 08:25:37

标签: angularjs

请问是否有任何方法可以捕获AngularJS中最后选择的单选按钮?

例如,我有以下代码呈现四个单选按钮:

<li ng-repeat="query in carousel.currentQuestionObject.choices" style="padding-bottom:5px;">
        <input class="TWInputField" 
               name="{{carousel.currentQuestionObject.name}}" 
               type="{{carousel.currentQuestionObject.inputType}}" 
               id="{{query.id}}"
               ng-model="carousel.checkboxCollection[query.id]" 
               ng-value="{{carousel.currentQuestionObject.value}}">

        <label for="{{query.id}}" 
               style="font-family:'MetricWeb-Regular';
                      font-size:17px;cursor:pointer">&nbsp;&nbsp;
               {{query.question}}
        </label>

我首先选择了3号电台,但后来改变了主意,选择了4号电台。然后我点击了此页面中的“下一步”按钮。

<div class="carousel-wizard-buttons" 
     ng-click="carousel.wizardNext(carousel.checkboxCollection)" 
     ng-hide="carousel.currentQuestionIndex == carousel.wizardQuestionSet.length - 1">
     Next
</div>

我的问题是,在检查了checkboxCollection之后,我看到单选按钮3和4的值都是真的,即使我只选择了#4。有什么方法可以告诉我的程序#3的值已经错了吗?

供您参考,这是我尝试做的事情(没有工作......):

vm.wizardNext = function(obj) {
    try {
            for (var i = 0; i < idxCnt; i++) {
                vm.checkboxCollection[i] = obj[i];
            }           
        }
        catch (err) {
            console.log(err);
        }
    // other code here
}

我在这里遗漏了什么吗?我应该怎么做呢?

enter image description here

希望得到你的意见。谢谢。

1 个答案:

答案 0 :(得分:0)

在遇到这个问题之后找到了一个解决方法:How to uncheck a radio button to make all objects become false。所以我修改了我的代码如下。希望这可以帮助那些有类似问题的人:

包含问题的数组:

{ inputType: "radio", name: 'qs1needs', question: "Tell us about your needs...", 
  choices: [
            { question: "I'm currently...", id: "qs1q1", selected:false },
            { question: "I'm currently...", id: "qs1q2", selected:false },
            { question: "I want to...", id: "qs1q3", selected:false },
            { question: "I want to...", id: "qs1q4", selected:false }
]}

HTML:

  • 更改了ng-model的值
  • 添加了ng-change,value和ng-value

    <input class="TWInputField" name="{{carousel.currentQuestionObject.name}}" 
           type="{{carousel.currentQuestionObject.inputType}}" id="{{query.id}}" 
           ng-model="query.selected" 
           ng-change="carousel.changeOnSelection(query.selected, query.id)"
           value="" ng-value="true">
    

AngularJS:

// Check values of radio buttons on change
    vm.changeOnSelection = function(selectedValue, selectedID) {

        // item refers to each item inside choices 
        angular.forEach(vm.currentQuestionObject.choices, function(item) {  
            /* since answer is already bound to model, 
               if selected ID is not equal to ID in focus, change value to false.
            */
            if (item.id !== selectedID) {                                       
                item.selected = false;
            }           

        });
    }