angularjsangularjs-controllerangular-ngmodelangularjs-ng-modelng-submit

ng-model not working with radio buttons in angular


I have a simple form with radio buttons that pulls values from a server and loops through them to provide radio buttons:

<form ng-submit="createSubCategory(subcategory)">
    <div ng-repeat="sub_category in event_sub_categories" >
        <label class="item item-radio">
                  <input type="radio" ng-model="subcategory" ng-value="'{{sub_category}}'" >
                  <div class="radio-content">
                    <div class="item-content">
                      {{sub_category}}
                    </div>
                    <i class="radio-icon ion-checkmark"></i>
                  </div>
         </label>
    </div>
    <div class="padding">
        <button type="submit" class="button button-block button-positive">Continue</button>
    </div>
</form>

The form displays perfectly. However, the radio button that I press doesn't seem to be saving. Here is the createSubCategory method:

$scope.createSubCategory = function(subcategory){
  console.log(subcategory);
}

The logs are showing undefined. How do I get the subCategory to be logged after filling out the form?


Solution

  • ng-repeat creates its own scope. Since you're binding your radio buttons to subcategory, what is populated is the ng-repeat scope's subcategory field, and not the controller scope's subcategory field.

    Rule of thumb:

    Also, ng-value expects an angular expression.

    So, in your controller, have this:

    $scope.formModel = {};
    

    And in the view:

    <input type="radio" ng-model="formModel.subcategory" ng-value="sub_category" >