Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript AngularJS单选按钮ng重复值_Javascript_Arrays_Angularjs_Radio Button - Fatal编程技术网

Javascript AngularJS单选按钮ng重复值

Javascript AngularJS单选按钮ng重复值,javascript,arrays,angularjs,radio-button,Javascript,Arrays,Angularjs,Radio Button,我正在使用ng repeat创建单选按钮,并希望所选按钮的名称值显示在下面 以下是我的看法: <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}}

我正在使用ng repeat创建单选按钮,并希望所选按钮的名称值显示在下面

以下是我的看法:

<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>


如何获得显示在段落标记中的权重?

您应该在
ng型号之一中保持radio的值
&使用$parent。要在控制器范围内而不是在
ng repeat
中定义它,请执行以下操作

标记

<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>

{{weight.name}
重量:{{radioValue}}


答案在于理解$scope在angular中是如何工作的。 快速解决方案是使用$parent.selectedName,其中$parent指的是父范围。这是因为ng repeat的每次迭代都会创建自身的范围。(见

看到这个了吗 JS是

function MyCtrl($scope) {

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

}

@Ryan很高兴能帮助你,谢谢:-)
function MyCtrl($scope) {

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