如何检查单选按钮Angular JS?

时间:2015-04-24 12:48:41

标签: angularjs

如何查看单选按钮? 如果$type == '1'检查输入并设置值= 1

,我需要这样做

我试过了:

第一个输入:

<input type="radio" 
       name="sex[]" 
       ng-init="formData.sex = '<?=($type == '1' ? '1' : null)?>" 
       ng-model="formData.sex"' 
       required>

第二次输入:

   <input type="radio" 
           name="sex[]" 
           ng-init="formData.sex = '<?=($type == '2' ? '2' : null)?>" 
           ng-model="formData.sex"' 
           required>

当我提交表单时,我看到formData.sex = true,因此Angular JS首先从第二个输入howether中获取值,因为条件$type == '1'为真。

2 个答案:

答案 0 :(得分:0)

您仍然需要一个值:

<input type="radio" 
   name="sex" 
   value="1"
   ng-init="formData.sex = '<?=($type == '1' ? '1' : null)?>" 
   ng-model="formData.sex"' 
   required>

<input type="radio" 
   name="sex" 
   value="2"
   ng-init="formData.sex = '<?=($type == '2' ? '2' : null)?>" 
   ng-model="formData.sex"' 
   required>

答案 1 :(得分:0)

尝试使用Plunker

查看此demo

如果type为1则检查第一个单选按钮;如果type为2则单击单选按钮2

这是你在寻找什么?

<body ng-app="radioExample">
  <script>
  angular.module('radioExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

      $scope.type = '2';

    }]);
</script>
<form name="myForm" ng-controller="ExampleController">

  <input type="radio" 
       name="sex" 
       value = '1'
       ng-init="{{sex = type == '1' ? '1' : '2'}}"
       ng-model="sex" 
       required> <label>1</label>

  <input type="radio" 
       name="sex" 
       value = '2'
       ng-init="{{sex = type == '2' ? '2' : '1'}}"
       ng-model="sex" 
       required> <label>2</label>

       <br/><br/> Sex is now {{sex}}

  </form>

</body>