简体   繁体   中英

Wrong radio input checked on load based on ng-model and ng-value

I have some basic example of form with 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>

As you can see, I'm not using ng-checked, just ng-model and ng-value. Also there are objects with properties printed, for comparison purposes.

Question is, why in every example, second radio button is checked, even if it's value is false - thus first radio which is truthy should be checked - ?

When I delete ng-value attributes from input, no radios are checked, even if properties from ng-models already have values which could make it happen..

When doing ng-repeat with objects, use (key, value) as the iterator:

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

It makes the HTML clearer.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM