简体   繁体   中英

Display selected radio button from the JSON input in Angularjs

I want the radio button to be selected depending on the input json values.

my json is

       "inventoryType": {
                        "bulk": [
                            {
                                "totalUnits": 80,
                                "addedOn": "12-01-2013"
                            }
                        ]
                    }

or

        "inventoryType": {
                        "day": [
                            {
                                "from": "12-Jan-2013",
                                "to": "12-Jan-2014",
                                "unitsPerDay": "30"
                            },
                            {
                                "from": "13-Jan-2014",
                                "to": "12-Jan-2015",
                                "unitsPerDay": "20"
                            }
                        ]
                    },

These are the 2 different data "bulk" and "day" for inventory type.

If I get data for bulk I want the bulk radio button to be selected else the vice versa.

Html code

<label class="span1">                                     
<input type="radio" name="optionsRadios" id="optionsRadios1" ng-value="{{productServiceInventory}}" ng-model="bulk" >
<small>Bulk</small>
</label>
<label class="span1">
<input type="radio" name="optionsRadios" id="optionsRadios2" ng-value="{{productServiceInventory}}" ng-model="day" >
<small>Day</small>
</label>

here the value of {{productServiceInventory}} is passed in the controller

if($scope.productServiceData.inventoryType.day === undefined){
console.log("bulk");
$scope.productServiceInventory = "bulk";
}
else if($scope.productServiceData.inventoryType.bulk === undefined){
console.log("day");
$scope.productServiceInventory = "day";
}

but my radio button is not getting selected to the appropriate data..

Kindly help me in selecting the radio button on json fetch.

Thanks in advance..

In your HTML, when you use ng-model="bulk" , you are referring to the entire array while $scope.productServiceInventory = "bulk" in your controller is a string. The radio button will be selected if both values are equal.

<label class="span1">                                     
<input type="radio" name="optionsRadios" id="optionsRadios1" ng-model="productServiceInventory" value="bulk" >
<small>Bulk</small>
</label>
<label class="span1">
<input type="radio" name="optionsRadios" id="optionsRadios2" ng-model="productServiceInventory" value="day" >
<small>Day</small>
</label>

There are other ways of achieving the same thing but this way, you can use your controller the way it is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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