1

I'm creating radio buttons with ng-repeat and would like the selected button's name value to appear below.

Here is my view:

<span ng-repeat="weight in weights">
  <input type="radio" name="weight" value="{{weight.name}}" id="weight{{weight.name}}" ng-checked="weight.checked">
  <label for="weight{{weight.name}}">{{weight.name}}</label>
</span>
<p>Weight: {{weight.name}}</p>

Here is my controller:

$scope.weights = [
  {
    name: 1,
    checked: true
  },
  {
    name: 2,
    checked: false
  },
  {
    name: 3,
    checked: false
  }
];

Here is my Plunker.

How can I get the weight to appear in the paragraph tag?

2 Answers 2

2

You should maintain value of radio in one of the ng-model & use $parent. to define it in controller scope rather than in ng-repeat like here

Markup

<body ng-controller="MainCtrl" ng-init="radioValue=1">
  <span ng-repeat="weight in weights">
    <input type="radio" name="weight" ng-model="$parent.radioValue" ng-value="{{weight.name}}" id="weight{{weight.name}}" ng-checked="weight.checked">
    <label for="weight{{weight.name}}">{{weight.name}}</label>
  </span>
  <p>Weight: {{radioValue}}</p>
</body>

Working Plunkr

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

Comments

0

The answer lies in understanding how $scope works in angular. The quick solution is to use $parent.selectedName, where $parent refers to the parent scope. This is because each iteration of ng-repeat creates a scope of itself. (see enter link description here

See this https://jsfiddle.net/pankaj01/Xsk5X/3074/ the JS is

function MyCtrl($scope) {

$scope.weights = [
  {
    name: 1,
    checked: true
  },
  {
    name: 2,
    checked: false
  },
  {
    name: 3,
    checked: false
  }
];

}

Comments

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.