0

I have a form that has a set of radio buttons (3 choices), and I am using angular and the ng-repeat directive to populate the html:

<div ng-repeat="fruit in fruitbasket">
  <input type="radio" name="fruit" data-ng-model="fruit.isSelected">{{fruit.id}}
</div>

the inside of the controller for the fruit basket looks like this:

$scope.fruitbasket = [{isSelected: false, id: "Orange", value: "1"}, {isSelected: true, id: "Pear", value: "2"}, {isSelected: false, id: "Apple", value: "3"}]

The choices in the view are Orange, Pear, and Apple, but after one is selected I want to pass the numeric "value"

Not sure how to do this in angular, I have tried several things, but non successful. Each time the passed value shows as nil

How does a connected element of an object get passed from a radio button in Angularjs?

1 Answer 1

2

Here's how you do it:

  1. isSelected is not needed. The fruitbasket is not part of your model, only the selected fruit is.

    $scope.fruitbasket = [
        {id: "Orange", value: "1"},
        {id: "Pear", value: "2"},
        {id: "Apple", value: "3"}
    ];
    
    $scope.model={selectedFruit:2};
    
  2. Assign the value (fruit.value) to each option and bind it to your model (model.selectedFruit)

    <input value="{{fruit.value}}" data-ng-model="model.selectedFruit" type="radio" name="fruit" > {{fruit.id}}
    

Check out this working plnkr example.

Sign up to request clarification or add additional context in comments.

6 Comments

@joakimbi In the scope of the model, why is selectedFruit set to 2?
I did it because in your question you had isSelected: true on "Pear". If you don't want to pre select an item you can just set $scope.model={};
@joakimbi when is use $scope.model={}; the object that gets passed is {"selectedFruit"=>"2"} but what I really need passed is just "2"... any thoughts?
Could you show me how you send the data - do you use $http, a $resource or something else?
@joakimbi through a fruits service, that uses $resource
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.