AngularJS radio buttons ng-repeat value

若如初见. 提交于 2021-01-28 10:07:22

问题


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?


回答1:


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




回答2:


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
  }
];

}



来源:https://stackoverflow.com/questions/29750708/angularjs-radio-buttons-ng-repeat-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!