sqlcte sqlcte - 2 years ago 109
Javascript Question

Angularjs unable to to bind radio buttons with model inside nested scopes

I have a scenario where I'm unable to bind radio buttons with my model.In my code radio buttons are being created dynamically inside ng-repeat which is inside ng-if.Here is my code

<div ng-if="Type.Value == 'Gadgets'">
<div class="form-group radioChkBtn">
<label class="col-sm-3 control-label">Device Type</label>
<div class="col-sm-7">
<div class="radio" ng-repeat="type in Types">
<input type="radio" ng-model="DeviceType" ng-value="{{type.Value}}" id="radioDeviceType{{$index}}" name="devicetype"><label for="radioDeviceType{{$index}}"> {{type.Value}}</label>


Value of DeviceType is always undefined.Even when I assign it some value none of the radio buttons is selected.ng-if creates a scope so is ng-repeat. May be it is the nesting of scopes which is causing the problem.Any help would be really appreciated.

Answer Source

Instead, try setting the model on radio select.

Have this in your controller:

$scope.onRadioChange = function(newValue) {
    $scope.DeviceType.value = newValue;

And make your HTML similar to this:

<div class="radio" ng-repeat="type in Types">
    <input type="radio" ng-model="DeviceType.value" ng-change="onRadioChange(type.Value)" ng-value="type.Value" id="{{type.Id}}" name="myRadios"><label for="{{type.Id}}"> {{type.Value}}</label>

So to break it down, we are now triggering the scope function onRadioChange() when the radio button is clicked via ng-change. We are passing the type.value to it, and inside the function making the model of DeviceType.value equal to the value that is passed to it.

In the example below, you can see that I output DeviceType.value on the page once a radio button is clicked and it has the same value as the radio button that is selected. I use DeviceType.value instead of just DeviceType to get around an Angular problem.


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