Reputation: 621
I'm having an object in my controller like the following:
$scope.colors = {
green: "Green",
yellow: "Yellow",
red: "Red"
};
I'm trying to create the radio inputs dynamically and then bind the value of the input to the object's key.
I'm trying something like this:
<label ng-repeat="color in colors">{{color}}
<input type="radio" ng-model="model.color" name="name" ng-value="{{color}}" ng-change="test()" />
</label>
but I can't make it work.
Here is my fiddle
Upvotes: 1
Views: 914
Reputation: 621
I managed to come with a cleaner solution.
<label ng-repeat="(key, value) in colors">
<input type="radio" ng-model="model.color" name="name" ng-value="key" /> {{value}}
</label>
here is the fiddle
Upvotes: 1
Reputation: 1907
you can do like this also :
<label ng-repeat="color in colors">{{color}}
<input type="radio" ng-model="colors" name="name" value="{{color}}" ng-change="test()" />
</label>
$scope.test = function() {
alert($scope.colors);
};
Upvotes: 0
Reputation: 2961
You never define your model on the controller. I have updated your fiddle to do so: https://jsfiddle.net/Xsk5X/1380/
$scope.model = {"color":"test"};
I also added a <span>
which displays the selected color to show it is working
I've added a new function and variable - $scope.createColors
and $scope.colorsToBind
.
The function will convert $scope.colors
into an array of just the object keys, and then create a new array of Objects containing the key and value for that color, but as accessible fields; each will look like {key:"green", value: "Green"}
. Once we have the array of these objects, the function will then set the value of $scope.colorsToBind
to that array.
Your html is now using that new variable colorsToBind
, and is displaying the value
of each object but binding to the key
of each one.
Upvotes: 2