angular js default checked radio button

时间:2017-11-08 22:10:09

标签: javascript angularjs radio-button radio-group

I know this has probably been asked many times before and I have been through the solutions but none seemed to have worked for me...

html file:

<input id="sampleA" name="try" type="radio" data-ng-model="$ctrl.isSampleA" value="true" data-ng-change="$ctrl.update()"></input>
<label for="sampleA">Sample A</label>
<input id="sampleB" name="try" type="radio" data-ng-model="$ctrl.isSampleA" value="false" data-ng-change="$ctrl.update()"></input>
<label for="sampleB">Sample B</label>

js file:

//Initialization:
vm.isSampleA = false;
//This function returns the correct boolean value returned by API
    vm.update = function() {
    vm.isSampleA = response.rows["0"].sampleA;
};

Briefly I'll explain the flow: The default check initially is 'Sample B' option. Then the user checks 'Sample A' option and sends the updated value to REST API, where it gets updated correctly. Next when I want to edit this form again:

Expected: 'Sample A' should be checked

Actual: none of the 2 options are checked, even though the value of 'isSampleA' is true.

1 个答案:

答案 0 :(得分:1)

使用ng-value指令代替普通value属性:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<script>
  angular.module('app', [])
</script>

<div ng-app='app' ng-init='test=true'>
  <label>
    <input type="radio" ng-model="test" ng-value="true">
    One
  </label>
  <br/>
  <label>
    <input type="radio" ng-model="test" ng-value="false">
    Two
  </label>
  <br/>
  <button ng-click='test = !test'>Click</button>
</div>