Amrita Singh
Amrita Singh

Reputation: 1

dynamic radio button generation in angularjs

From this json array I need to build dynamic radio buttons with mobile numbers in angularjs:

challengeSelectInfo:
[
    {"mob_0" : "xxxxx1211"},
    {"mob_1" : "xxxxx1211"},
    {"mob_2" : "xxxxx1211"}
]

I tried ng-repeat and iterate over challengeSelectInfo but the issue that I'm facing is keys(mob_0,mob_1,mob_2) are different and I'm unable to generate dynamic radio buttons.

Any help is appreciated.

Thanks

Upvotes: 0

Views: 1231

Answers (3)

Anil Talla
Anil Talla

Reputation: 709

Can you check this JSFIDDLE Example

  var data = {  "challengeSelectInfo" : [ {"mob_0" : "xxxxx1211"},
   {"mob_1" : "xxxxx1211"}, {"mob_2" : "xxxxx1211"} ]}
  $scope.radioGrp = (data['challengeSelectInfo'] || []).map(function(obj){      
       for(var i in obj){ 
          return { 'value': i, 'name': obj[i] }; 
       } 
     });

 <input type="radio" ng-repeat="rb in radioGrp" ng-value="rb.value" ng-modal="radioValue" name="{{rb.name}}">

Upvotes: 0

Sa E Chowdary
Sa E Chowdary

Reputation: 2075

made this simply for your understanding purpose hope you can achieve your requirement by using this

  var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.challengeSelectInfo= [
    {"mob_0" : "xxxxx1211"},

{"mob_1" : "xxxxx1211"},

{"mob_2" : "xxxxx1211"} ];


});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
   <div ng-repeat="(k,v) in challengeSelectInfo ">
     <div ng-repeat="(x,y) in v">
      <input type="radio" />{{y}}
     </div>
   </div>
   </body>
  

</html>

Upvotes: 0

digit
digit

Reputation: 4565

You need to specify keys for your arrays :

$scope.newArr = [];
angular.forEach(challengeSelectInfo, function(val, key) {
    /* do something for all key: value pairs */
     $scope.newArr.push({id: key, value: val});
});

Then loop through newArr arrays and assign to radio button :

<input name="{{item.value}}" type="radio" ng-model="item.id" value="{{item.value}}">

Upvotes: 1

Related Questions