ohboy21
ohboy21

Reputation: 4319

How to get ng-repeat radio-button value inside the controller?

I have a form, within there are different input-tags and labels :

form action="">
  <div class="fields" data-ng-repeat="option in question.body.options">
        <input id="{{option.text}}" type="radio" name="gender" ng-model="demographic_value" ng-value="{{option.text}}">
        <label for="{{option.text}}">{{option.text}}</label>
    </div>
</form>

I want to access the value of the selected radio button, how is the data binded? Is there any standard-method, or "isChecked" value or something like that?

EDIT: OK, to be more clear: I want to have only the option which is selected. Inside the controller, not in the view.

So i can send the selected value over HTTP to a server.

  1. Click a radio button
  2. do something like var checked = $scope.radiobutton
  3. array.push(checked)
  4. Send over to a server

Upvotes: 3

Views: 2978

Answers (2)

Artyom Pranovich
Artyom Pranovich

Reputation: 6962

Use a shared service and inject it to any controllers:

    angular.module("yourAppName", []).factory("mySharedService", function(){

        var mySharedService = {};

        mySharedService.values = {};

        mySharedService.setValues = function(params){
            mySharedService.values = params;
        }

          return mySharedService; 
   });

And after inject it into any controller. For example:

function MainCtrl($scope, myService) {
  $scope.radioButtons= myService.values;
}

function AdditionalCtrl($scope, myService) {
  $scope.var= myService.values;
}

EDIT: as for checked/unchecked values:

You can use watcher:

$scope.$watch('question.body.options', function (changedOptions) {
    //some actions with changed options
}, true);

UPDATE: As for your update:

1) You should create watcher, such as above.

2) Into the watcher, when value changes - you initialize necessary service property with your values (call setValue function)

3) You should inject sharedService into another controller, and can get these values from this service.

4) Call $http or $resource method to sent this value on server.

Upvotes: 1

Banana-In-Black
Banana-In-Black

Reputation: 2557

  1. ng-repeat creates its own scope for each item, so you might have problem accessing it. Try put the model in an object from parent scope.
  2. ng-value accepts expression but not like {{expression}}.

http://jsfiddle.net/g8qLY/

HTML:

<form ng-app ng-controller="ctrl" name="inputform">
    <label for="{{option}}" ng-repeat="option in options">
        {{option}}
        <input id="{{option}}" type="radio" name="gender" 
            ng-model="inputform.radioinput" ng-value="option">
    </label>
    <div ng-bind-template="Radio Input: {{inputform.radioinput}}"/>
</form>

JS:

function ctrl($scope) {
    $scope.options = ['Option1', 'Option2', 'Option3'];
}

Upvotes: 1

Related Questions