根据ng模型和ng值在负载上检查了错误的无线电输入

时间:2018-07-25 17:29:38

标签: javascript angularjs forms object

我有一个radio inputs DEMO on PLNKR形式的基本示例:

<form class="some-inputs">
    <div ng-repeat="da in data">
      <span>{{$index}}: {{da}}</span>
      <label>
        <input type="radio" id="lock-{{$index}}"
               name="lock-choice-{{$index}}"
               ng-model="mdl['account-{{$index}}']['blocked']"
               ng-value="da.blocked">
        <span>blocked</span>
      </label>
      <label>
        <input type="radio" id="unrealized-{{$index}}"
               name="lock-choice-{{$index}}"
               ng-model="mdl['account-{{$index}}']['unrealized']"
               ng-value="da.unrealized">
        <span>not blocked</span>
      </label>
    </div>
</form>

如您所见,我没有使用ng-checked,而是使用ng-model和ng-value。 还有一些带有打印属性的对象,用于比较。

问题是,为什么在每个示例中都检查第二个单选按钮,即使它的值是false-因此也应检查第一个为真的单选按钮-吗?

当我从输入中删除ng-value属性时,即使ng-models中的属性已经具有可以使其实现的值,也不会检查任何无线电。

1 个答案:

答案 0 :(得分:0)

对对象进行ng-repeat时,请使用(key, value)作为迭代器:

̶<̶d̶i̶v̶ ̶n̶g̶-̶r̶e̶p̶e̶a̶t̶=̶"̶d̶a̶ ̶i̶n̶ ̶d̶a̶t̶a̶"̶>̶
<div ng-repeat="(key,da) in data">

它使HTML更清晰。

The DEMO

angular.module('app', [])
.controller('ctrl', function($scope) {
  $scope.data = {
    "account-0":{
      "blocked":true,
    },
    "account-1":{
      "blocked":false,
    },
    "account-2":{
      "blocked":false,
    },
    "account-3":{
      "blocked":true,
    }
  };
  $scope.mdl = {};
  angular.forEach($scope.data, (value, key)=> {
    $scope.mdl[key] = {choice: value.blocked?'blocked':'not blocked'};
  });
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
  <form name="form1">
    <div ng-repeat="(key, da) in data">
      <span>{{key}}</span>
      <label>
        <input type="radio" id="{{key}}-blocked"
               name="block-choice-{{key}}"
               ng-model="mdl[key].choice"
               ng-value="'blocked'">
        <span>blocked</span>
      </label>
      <label>
        <input type="radio" id="{{key}}-not-blocked"
               name="block-choice-{{key}}" 
               ng-model="mdl[key].choice"
               ng-value="'not blocked'">
        <span>not blocked</span>
      </label>
      <label>
        <input type="radio" id="{{key}}-undecided"
               name="block-choice-{{key}}" 
               ng-model="mdl[key].choice"
               ng-value="'undecided'">
        <span>undecided</span>
      </label>
    </div>
    <hr>
    <div ng-repeat="(k,v) in mdl">
    {{k}} {{v}}
    </div>
  </form>
</body>