0

I have 2 radio input fields

<input type="radio" name="location_type" ng-model="location_type" value="ANYWHERE" required> Anywhere
<input type="radio" name="location_type" ng-model="location_type" value="FIXED" required> Fixed

If the selected radio is value is "FIXED", another text field is displayed using ng-if. This text field have 'required' validation.

<div ng-if="location_type == 'FIXED'">
    <input type="text" class="form-control" name="city" ng-model="city" placeholder="Enter City" ng-blur="cname=''" ng-focus="cname='bold'" required>
</div

I do not get the value of $scope.city in controller because the input city is displayed dynamically when I click on the radio button with value value FIXED.

If I use ng-show instead of ng-if, I get the $scope.city variable value in controller, but in that case the validation for city input is working even when I select radio button ANYWHERE. The city field will be hidden and its validation need not work when I select radio button ANYWHERE.

Who can make my day :)

1
  • Just try use ng-required="location_type=='FIXED'" on input. Commented Sep 5, 2016 at 6:08

2 Answers 2

2

ng-if directive create new child scope.

As per your your html, you are assigning city to this child scope and not the parent scope which is your controller.

So,not accessible in controller.

So, you need to do something like this.

Declare object in parent controller like this ;

$scope.parentObj = {};

And change your html ;

<input type="text" class="form-control" name="city" ng-model="parentObj" required>

Now, your child scope will get the inherited object property from controller;

So, it will reflect in controller.

Here is the working Plunker

Sign up to request clarification or add additional context in comments.

3 Comments

Need not initialize element inside parentobj. $scope.parentObj={} works
Thanks for the solution
ok, can you remove the city parameter as empty from parentObj initialize, as its actually not required.
0

Have you tried ng-required="boolValueOrExpression" ? It's a conditionally validation in your case.

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.