1

I have a form using AngularJS (classic one) that should display or not a CompanyName field only if the User is a Company.

By default the "Individual" radio should be selected:

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

How to bind to the radio checked value in order to make it work?

2 Answers 2

1

I added a ng-model and ng-value to both inputs, so when you will click again on "an individual", the company form will disapear.

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


Note that I added ng-init="user.isCompany = false" in <body>. You can also move it to your controller to make it cleaner:

$scope.user = { ..., 'isCompany': false };
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.