javascript - 在选择时为单选按钮分配唯一的 ID

标签 javascript angularjs

我正在尝试将唯一的 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/

相关文章:

javascript - jQuery ColorBox 确认覆盖模式对话框吗?

javascript - 观察 angularjs $rootScope 变量

javascript - Bootstrap 3 悬停时折叠

javascript - 无法从 backbone.js 教程填充 Backbone 集合

javascript - JavaScript 数组克隆相等断言中的奇怪行为

angularjs - ui-bootstrap-tpls.min.js 和 ui-bootstrap.min.js 有什么区别?

javascript - 具有多个模块的路由和内联 View 不起作用 - $http 拦截器可能会导致错误

javascript - JS Gmaps API,如何从开放标记和中心标记的 href 值序列化数据?

javascript - Angular将csv文件上传到范围内而不发布到服务器

javascript - 如何使用angularjs在选择标签中使用select2显示标签