Search code examples
angularjsdynamicscopeangular-ng-if

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>
</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 :)


Solution

  • 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