Reputation: 83
I am a complete beginner at using Angular.js and I've run into an issue with data binding in a radio button situation. The related HTML code looks like this:
<label class="options_box" ng-repeat="item in item_config_list.item_config">
<input type="radio" name="config" ng-model="selectedConfig" ng-value="item">
{{ item.item }}
</input>
</label>
and controller is
App.controller('controller', function App ($scope, $http) {
$.getJSON('res/prop/configs.json', function(data) {
$scope.item_config_list = data;
});
json file looks like this:
{
"item_config": [
{
"name": "Config1",
"configNr": "1"
},
{
"name": "Config2",
"configNr": "2"
},
]
}
How do I make the name property of the selected item from the radio list go into the "selectedConfig" object? I am later referring to the selectedConfig object to fetch data from a backend.
I might also add that the duplication of radio buttons is working - as is the labelling of the buttons. They are named properly, they just aren't conferring the intended value to the intended object.
Edit: Problem solved! I refactored above HTML code to
<label class="options_box" ng-repeat="item in item_config_list.item_config">
<input type="radio" name="config" ng-model="$parent.selectedConfig" ng-value="item.name">
{{ item.name }}
</input>
</label>
Upvotes: 2
Views: 3007
Reputation: 2671
Please use different "name" attribute for all the input fields in being generated using the ng-repeat.
Something like below :
<input type="radio" name="config{{$index}}" ng-model="selectedConfig" ng-value="item.item">
{{ item.item }}
</input>
Please look at the following plnkr : http://plnkr.co/edit/RQQi5Fo9FzM409qKHwjG?p=preview
I hope this will do the trick
Upvotes: 0
Reputation: 3062
I think you just need to change the ng-value
binding:
<input type="radio" name="config" ng-model="selectedConfig" ng-value="item.item">
{{ item.item }}
</input>
That should then bind the name string in item.item
to your scope's selectedConfig
Slight confusion from your ng-repeat
objects being called item
and the first property of each object in that collection is also called item
UPDATE:
From the fiddle you provided I have a working example for you to look at:
https://jsfiddle.net/sc622go8/
The underlying issue was that the ng-repeat
creates a child scope, so to refer to the selectedConfig
variable, you need to use $parent.selectedConfig
:
<input type="radio" name="config" ng-model="$parent.selectedConfig" ng-value="item.item">
{{ item.item }}
</input>
Upvotes: 1