2

I have a radio button and a text field. I want the text field to be required only if the radio button is ticked.

<label class="radio">
    <input type="radio" value="createNewCollection" ng-model="selectedCollection" />
</label>
<input type="text" ng-model="collectionName" placeholder="Create new Collection"/>

So, collectionName is only required if createNewCollection is selected.

Hans Andersen
  • 23
  • 1
  • 4
  • possible duplicate of [How can I conditionally require form inputs with AngularJS?](http://stackoverflow.com/questions/13466133/how-can-i-conditionally-require-form-inputs-with-angularjs) – New Dev Mar 01 '15 at 02:32
  • Welcome to Stack Overflow! Don't forget to take a few minutes to read through the tour: http://stackoverflow.com/tour Your question will probably be closed because it is a duplicate, but I looked first and didn't find a similar question, so no worries! This post may help others find what they're looking for. Do make sure to look for other posts that address your issue before posting new ones. – m59 Mar 01 '15 at 02:35

1 Answers1

4

angular.module('myApp', []);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form name="form" ng-app="myApp">
  <label class="radio">
    <input type="radio" value="createNewCollection" ng-model="selectedCollection">
  </label>
  <input type="text" name="input" ng-required="selectedCollection" ng-model="collectionName" placeholder="Create new Collection">
  <p ng-show="form.input.$error.required">This is required.</p>
</form>

You need to set the ng-required attribute of that input to the model name of the radio input. ng-required="selectedCollection"

Read the docs here.

m59
  • 43,214
  • 14
  • 119
  • 136
  • This worked, i tried the using the ng-required and ng-value early but it didnt work. Thank for the new ngShow directive. – Hans Andersen Mar 01 '15 at 03:23