Smitha Smitha - 1 year ago 133
jQuery Question

Bind a single ng-model for 2 ng-repeat in Angular Radio button

I have two different lists, which I need to display as a single list on a page and show as a radio items in a screen. How to identify the ng-model and selected values if no element is chosen or by default if user selects the default value.



<script>
angular.module('valueExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.names = ['pizza', 'unicorns', 'robots'];
$scope.my = { favorite: 'unicorns' };
}]);
</script>
<form ng-controller="ExampleController">
<h2>Which is your favorite?</h2>
<label ng-repeat="name in names" for="{{name}}">
{{name}}
<input type="radio"
ng-model="my.favorite"
ng-value="name"
id="{{name}}"
name="favorite">
</label>
<label ng-repeat="name in names2" for="{{name}}">
{{name}}
<input type="radio"
ng-model="my.favorite"
ng-value="name"
id="{{name}}"
name="favorite">
</label>
<div>You chose {{my.favorite}}</div>
</form>





names and names2 are 2 list items, which i want to display on single screen

Dev Dev
Answer Source

As I suggested, you can concat lists and use ng-repeat accordingly. Or you can use ng-repeat-start and ng-repeat-end and render accordinly.

 angular.module('valueExample', [])
   .controller('ExampleController', function($scope) {
     var names1 = ['pizza1', 'unicorns1', 'robots1'];
     var names2 = ['pizza2', 'unicorns2', 'robots2'];
     $scope.names = names1.concat(names2);
     $scope.my = {
       favorite: 'unicorns1'
     };
   });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script>
<form ng-app="valueExample" ng-controller="ExampleController">
  <h2>Which is your favorite?</h2>
  <div ng-repeat="name in names">
    <input type="radio" ng-model="my.favorite" ng-value="name" />
    <label>{{name}}</label>
  </div>

  <div>You chose {{my.favorite}}</div>
</form>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download