简体   繁体   English

使用AngularJS验证单选按钮

[英]Validation on radio buttons with AngularJS

I have a cross platform app that uses AngularJS, Monaca and Onsen UI. 我有一个使用AngularJS,Monaca和Onsen UI的跨平台应用程序。

On one of my views I have an array of list items, and each list item can have have a random amount of radio buttons associated with it. 在我的一个视图中,我有一个列表项数组,每个列表项可以具有与之关联的随机数量的单选按钮。

The list array is built at runtime from a JSON that is returned via an API call. list数组是在运行时根据通过API调用返回的JSON构建的。 An example of my JSON is below: 我的JSON示例如下:

[{
    "fruitID": "1",
    "fruitname": "Apple",
    "options": [{
        "optionID": "1",
        "optiondescription": "Has seeds"
    }, {
        "optionID": "2",
        "optiondescription": "Can be eaten raw"
    }, {
        "optionID": "3",
        "optiondescription": "Has edible skin"
    }]
}, {
    "fruitID": "2",
    "fruitname": "Banana ",
    "options": [{
        "optionID": "1",
        "optiondescription": "Has no seeds"
    }, {
        "optionID": "2",
        "optiondescription": "Can be eaten raw"
    },
        {
        "optionID": "3",
        "optiondescription": "Needs to be peeled"
    },
        {
        "optionID": "4",
        "optiondescription": "Short shelf life"
    }]
}]

So for instance the list may contain a random number of fruit items and each fruit may have a random number of options associated with it. 因此,例如,列表可能包含随机数量的水果项目,并且每个水果可能具有与之关联的随机数量的选项。 Eg 例如

- Apple (1) -- Has seeds (1) -- Can be eaten raw (2) -- Has edible skin (3) -苹果(1) -有种子(1)-可以生吃(2)-有食用皮(3)

- Banana (2) -- Has no seeds (1) -- Can be eaten raw (2) -- Needs to be peeled (3) -- Short shelf life (4) -香蕉(2) -没有种子(1)-可以生吃(2)-需要去皮(3)-保质期短(4)

- Pineapple (3) *-- Can be eaten raw (1) -- Needs to be peeled (2) -菠萝(3) *-可以生吃(1)-需要去皮(2)

For each fruit, the user must select one option. 用户必须为每种水果选择一个选项。 When the user selects an option, I need to save both the fruitID eg Banana (2) as well as the optionID eg Can be eaten raw (2) so that these values can be sent back to my Database as a JSON. 当用户选择一个选项时,我需要同时保存fruitID(例如Banana (2))和optionID(例如可以原始食用 (2)),以便可以将这些值作为JSON发送回我的数据库。

At the moment I register events on the radio buttons in my view via an ng-click() and pass the function in my controller the values of fruitID and optionID as follows: 现在,我通过ng-click()在视图中的单选按钮上注册事件,并在控制器中将该函数的fruitIDoptionID传递如下:

<ul class="list">
    <li class="list__item" ng-repeat="checkFruitDescription in data"> <!-- Where data is the JSON -->
        <span class="list__item__line-height"><strong>{{checkFruitDescription.fruitname}}</strong></span>

        <label class="radio-button" ng-repeat="option in checkFruitDescription.options">
            <input type="radio" 
                name="option_question_id_{{checkFruitDescription.fruitID}}" 
                ng-model="checkFruitDescription.selected_id"
                ng-click="doSomething(checkFruitDescription.fruitID, option.optionID)"
                ng-value="option.optionID">
            <div class="radio-button__checkmark"></div>

             Description: {{option.optiondescription}}
        </label>
    </li>
</ul>

In my doSomething() function I want to save the values of fruitID and optionID for each radio button selected to an array (is this the best option?). 在我的doSomething()函数中,我想将每个选中的单选按钮的fruitIDoptionID的值保存到数组中(这是最好的选择吗?)。 However, I need to validate the radio buttons - so if the user select an option for Apples but then changes their mind, I need to update the values currently stored. 但是,我需要验证单选按钮-因此,如果用户为Apple选择一个选项,但随后改变了主意,则需要更新当前存储的值。

In my doSomething() function I tried: 在我的doSomething()函数中,我尝试过:

$scope.selectedRadioArray = [];

$scope.doSomething = function(fruitID, optionID)
{
    // Where data = JSON
    if ($scope.data.fruitID.indexOf(fruitID) != -1)
    {
        // There is a match for fruitID in data.fruitID
        // Save the values to an array
        $scope.selectedIDS = [fruitID, optionID];

        // Push the array to a new array
        $scope.selectedRadioArray.push($scope.selectedIDS);
    }
    else
    {
        // Do something else
    }
}

But I run into issues here. 但是我在这里遇到了问题。 Saving the selectedIDS array to the selectedRadioArray works, but: selectedIDS数组保存到selectedRadioArray可以,但是:

  • Sorting through the array to match the fruitID to the optionID becomes very difficult 对数组进行排序以使fruitIDoptionID匹配变得非常困难
  • If the user changes their mind and selects a new optionID for eg Apple, then the old value still remains in the database. 如果用户改变主意并为Apple选择新的optionID,则旧值仍保留在数据库中。 I tried to implement the indexOF() function, but the issue there is that optionID is the same for a lot of the fruit options (1, 2, 3, ...). 我尝试实现indexOF()函数,但是问题是,对于许多水果选项(1、2、3,...), optionID都是相同的。 So if I check the indexOF() optionID for Apples it may return that it is already selected, even though it may be finding the value for Bananas. 因此,如果我检查了Apple的indexOF() optionID ,即使它正在查找Bananas的值,它也可能返回它已被选择的状态。

What is the best way to handle validation on radio buttons and what is the best way to save the values that are returned on radio button clicks? 处理单选按钮验证的最佳方法是什么,保存单选按钮单击返回的值的最佳方法是什么?

You can save yourself the hassle of manually picking out the fruitID and optionID by defining them as in one object in the ng-value of the radio buttons, like this: 通过在单选按钮的ng-value的一个对象中定义它们,您可以省去手动选择fruitID和optionID的麻烦,如下所示:

ng-value="{fruit: checkFruitDescription.fruitID, option: option.optionID}"

this way the checkFruitDescription.selected_id holds both the fruitID and selected option. 这样, checkFruitDescription.selected_id保存fruitID和selected选项。 You can take it 1 step further and make an adjustment to the ng-model of the radio buttons to make the radio buttons function without writing any code in the controller: 您可以更进一步,并对单选按钮的ng-model进行调整,以使单选按钮起作用,而无需在控制器中编写任何代码:

ng-model="selectedArray[$parent.$index]"

Now the selectedArray contains all the results. 现在,selectedArray包含所有结果。 Just keep in mind to create the selectedArray in your controller first. 请记住,首先要在控制器中创建selectedArray。 Here's a plunkr: http://plnkr.co/edit/IgpAXu8tbKUXj9ACPtZs?p=preview 这是一个插件: http ://plnkr.co/edit/IgpAXu8tbKUXj9ACPtZs?p=preview

Apply this code: 应用此代码:

$scope.selectedRadioArray = [];

$scope.doSomething = function(fruitID, optionID) {
var status = 0;
if ($scope.selectedRadioArray.length > 0) {
    // check whether selected fruit exists into array or not 
    $scope.selectedRadioArray.forEach(function(e, i) {
        if (e.fruitID == fruitID) {
            // updates option ID into same array position
            $scope.selectedRadioArray[i] = {
                fruitID: e.fruitID,
                optionID: optionID
            };
            status = 1;
        }
    });
    // if this fruit id not available then save it into array
    if (status != 1) {
        var fruits_row = {
            fruitID: fruitID,
            optionID: optionID
        };
        $scope.selectedRadioArray.push(fruits_row);
    }
} else {
    // if there is no  value into array
    var fruits_row = {
        fruitID: fruitID,
        optionID: optionID
    };
    $scope.selectedRadioArray.push(fruits_row);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM