角度绑定无线电到布尔值不起作用

时间:2017-03-22 13:42:14

标签: angularjs radio-button

我有一个使用AngularJS(经典之作)的表单,只有在用户是公司时才应显示或不显示CompanyName字段。

默认情况下,应选择“Individual”收音机:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<body ng-app>
  <h4>You are:</h4> 
  Name <input ng-model="user.name">
  <h5>Individual or Company?</h5>

  <input type="radio" name="type" id="company" ng-model="user.isCompany" ng-value=true> a company = '{{user.isCompany}}'<br>
  <input type="radio" name="type" id="individ" checked > an individual<br>

  <div ng-show="user.isCompany">
    Company Name <input ng-model="user.companyName">
  </div>
</body>

如何绑定到收音机选中的值以使其正常工作?

2 个答案:

答案 0 :(得分:1)

我在两个输入中添加了ng-modelng-value,因此当您再次点击&#34;个人&#34;时,公司表单将会消失。

&#13;
&#13;
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<body ng-app ng-init="user.isCompany = false">
  <h4>You are:</h4> 
  Name <input ng-model="user.name">
  <h5>Individual or Company?</h5>

  <input type="radio" name="type" ng-model="user.isCompany" ng-value="true"> a company = '{{user.isCompany}}'<br>
  <input type="radio" name="type" ng-model="user.isCompany" ng-value="false"> an individual<br>

  <div ng-show="user.isCompany">
    Company Name <input ng-model="user.companyName">
  </div>
</body>
&#13;
&#13;
&#13;

请注意,我在ng-init="user.isCompany = false"中添加了<body>。您也可以将其移动到控制器以使其更清洁:

$scope.user = { ..., 'isCompany': false };

答案 1 :(得分:0)

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<body ng-app>
  <h4>You are:</h4> 
  Name <input ng-model="user.name">
  <h5>Individual or Company?</h5>

  <input type="radio" name="type" id="company" ng-model="user.isCompany" ng-value="true"> a company = '{{user.isCompany}}'<br>
  <input type="radio" name="type" id="individ" ng-init="user.isCompany=false" ng-model="user.isCompany" checked ng-value="false"> an individual<br>

  <div ng-show="user.isCompany">
    Company Name <input ng-model="user.companyName">
  </div>
</body>