mirza vu mirza vu - 1 year ago 66
AngularJS Question

Angularjs accessing scope for dynamic elements

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>

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

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

Who can make my day :)

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download