我正在尝试将唯一的 ID 分配给选择的单选按钮。我不确定这是正确的方法。我尝试过这样的:
<!DOCTYPE html>
<html ng-app="radioExample">
<head>
<script data-require="angular.js@1.5.6" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script>
<link href="style.css" rel="stylesheet" />
<script src="script.js"></script>
</head>
<body>
<script>
angular.module('radioExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.startDate = {
id: new Date()
};
$scope.specialValue = {
"value": new Date().getMilliseconds()
};
$scope.uniqueId = new Date().getMilliseconds();
}]);
</script>
<form ng-controller="ExampleController" name="myForm">
<label>
<input type="radio" name="rdboption" ng-value="specialValue" ng-model="startDate.id" id="{{::uniqueId}}" />
Jan
</label>
<br />
<label>
<input type="radio" name="rdboption" ng-value="specialValue" ng-model="startDate.id" id="{{::uniqueId}}" />
Feb
</label>
<br />
<label>
<input type="radio" name="rdboption" ng-value="specialValue" ng-model="startDate.id" id="{{::uniqueId}}" />
Mar
</label>
<br />
<tt>ID = {{uniqueId | json}}</tt>
<br />
</form>
Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
</body>
</html>
即使添加了以毫秒为单位的时间戳,这也会为所有单选按钮打印相同的值
最佳答案
它添加了相同的值,因为它是相同的值,您只使用一个变量,在 Controller 上分配一次,然后使用相同的变量三次。
无论如何,为什么你需要为每个输入分配一个唯一的 ID。
您可以解决这个问题,在 Controller 上声明一个返回唯一 ID 的函数,然后从您的 View 中调用它。
关于javascript - 在选择时为单选按钮分配唯一的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38093497/