AngularJS 具有名称属性的单选按钮组未正确初始化
AngularJS radio button groups with name attribute not initializing properly
如果我们为组指定 name
属性,则单选按钮组似乎不会在 ng-repeat
块内初始化 属性。它似乎适用于最后一组无线电组,但不适用于其余组。此外,如果我删除 name
属性,它也能正常工作。根据 [AngularJS 文档][1],如果我们将它与 ngModel
一起使用,则不需要 name
属性。但它并没有说我们不能使用它。我需要指定一个 name
属性。
请参考下例:
var m = angular.module("MyApp", []);
m.controller("MyController", ["$scope", function($scope) {
$scope.myArr = [{
name: "Obj 1",
status: "a"
}, {
name: "Obj 2",
status: "b"
}, {
name: "Obj 3",
status: "c"
}];
}]);
body {
background-color: #1D1F20;
}
.row {
margin-bottom: 15px;
}
.demo {
background: green;
color: white;
padding: 10px;
border-radius: 3px;
min-width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyController" class="demo">
<div ng-repeat="eachItem in myArr" class="row">
<span>{{eachItem.name}} => </span>
<label> a
<input name="status-$index" type="radio" ng-model="eachItem.status" value="a">
</label>
<label> b
<input name="status-$index" type="radio" ng-model="eachItem.status" value="b">
</label>
<label> c
<input name="status-$index" type="radio" ng-model="eachItem.status" value="c">
</label>
</div>
</div>
除了将名称属性设置为输入的地方外,您的代码看起来不错。
模板中的 $index
仅当您将其括在花括号中时才会被评估。
例如:{{$index}}
否则您将在名称中得到 $index。你应该使用:
<div ng-repeat="eachItem in myArr track by $index" class="row">
<input name="status-{{$index}}" type="radio" ng-model="eachItem.status" value="a">...
</div>
如果我们为组指定 name
属性,则单选按钮组似乎不会在 ng-repeat
块内初始化 属性。它似乎适用于最后一组无线电组,但不适用于其余组。此外,如果我删除 name
属性,它也能正常工作。根据 [AngularJS 文档][1],如果我们将它与 ngModel
一起使用,则不需要 name
属性。但它并没有说我们不能使用它。我需要指定一个 name
属性。
请参考下例:
var m = angular.module("MyApp", []);
m.controller("MyController", ["$scope", function($scope) {
$scope.myArr = [{
name: "Obj 1",
status: "a"
}, {
name: "Obj 2",
status: "b"
}, {
name: "Obj 3",
status: "c"
}];
}]);
body {
background-color: #1D1F20;
}
.row {
margin-bottom: 15px;
}
.demo {
background: green;
color: white;
padding: 10px;
border-radius: 3px;
min-width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyController" class="demo">
<div ng-repeat="eachItem in myArr" class="row">
<span>{{eachItem.name}} => </span>
<label> a
<input name="status-$index" type="radio" ng-model="eachItem.status" value="a">
</label>
<label> b
<input name="status-$index" type="radio" ng-model="eachItem.status" value="b">
</label>
<label> c
<input name="status-$index" type="radio" ng-model="eachItem.status" value="c">
</label>
</div>
</div>
除了将名称属性设置为输入的地方外,您的代码看起来不错。
模板中的$index
仅当您将其括在花括号中时才会被评估。
例如:{{$index}}
否则您将在名称中得到 $index。你应该使用:
<div ng-repeat="eachItem in myArr track by $index" class="row">
<input name="status-{{$index}}" type="radio" ng-model="eachItem.status" value="a">...
</div>