0

I have created radio buttons in angularjs using array of objects using ng-value and ng-model.

`

<div ng-controller="DemoController">
      <div ng-repeat="detail in details">
          <input type="radio" ng-model="$parent.selectedVal" ng-value="detail" name="test">
      </div>       
      {{selectedVal}}
  </div>

` On selection of radio button model is populated with corresponding object value. But I am not sure how to initialize it using controller with object.

 var app = angular.module('myApp', []);
app.controller("DemoController",DemoController);
function DemoController($scope) {
    $scope.selectedVal={name:"Def",age:4} ;
    $scope.details=[{name:'Abc',age:2},{name:'Xyz',age:3},{name:'Def',age:4}];
  }
4
  • You should do $scope.selectedVal=$scope.details[3]; to select the third value. Commented Apr 26, 2015 at 8:17
  • 1
    Are you sure the JsFiddle link is correct ? Commented Apr 26, 2015 at 8:18
  • @Chandermani Thanks but I have a use case, when Page is loading I am making two service call one to render radio buttons and another to populate radio button with already selected value (which is saved in database). If I implement solution which you have provided then I have to iterate complete array e.g. $scope.details in my example to find out index of that already selected value and initialize model with that value. Is there any other clear way to do it ? Commented Apr 27, 2015 at 6:33
  • @Ofiris Yes I noticed I mistakenly put another JSFiddle link. Commented Apr 27, 2015 at 6:37

1 Answer 1

1

You should reference the selected value from the details array instead of creating a new instance:

$scope.details = [{ name:'Abc', age:2 }, { name:'Xyz', age:3 }, { name:'Def', age:4 }];    
$scope.selectedVal = $scope.details[2];

This will select the last of the 3 radio buttons. Also if both details and selectedVal are defined within the same scope you should update your radio button as well, it's quite unclear why you referenced selectedVal from a $parentScope:

<input type="radio" ng-model="selectedVal" ng-value="detail" name="test" />

And here's the updated fiddle: https://jsfiddle.net/sb3krc8c/2/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Darin but I have a use case, when Page is loading I am making two service call one to render radio buttons and another to populate radio button with already selected value (which is saved in database). If I implement solution which you have provided then I have to iterate complete array e.g. $scope.details in my example to find out index of that already selected value and initialize model with that value. Is there any other clear way to do it ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.