I'm trying to build a color configurator in AngularJS using radio buttons and everything seems to be working, the data binds, etc... but I'm not able to set the default color radio button checked. As I see in the docs if the ng-model is the same as the radio value the input should be auto-checked but I don't know if this only work for strings and not for objects.
This is the HTML:
<div ng-app ng-controller="ThingControl">
<ul >
<li ng-repeat="color in colors">
<input type="radio" ng-model="thing.color" value="{{color}}" />{{ color.name }}
</li>
</ul>
Preview: {{ thing }}
</div>
And this is the JS:
function ThingControl($scope){
$scope.colors = [
{ name: "White", hex: "#ffffff"},
{ name: "Black", hex: "#000000"}
]
$scope.thing = {
color: $scope.colors[1]
}
}
You can see the previous example in this fiddle: http://jsfiddle.net/xWWwT/1/
Thanks very much in advance!
Selection is matched by the string defined in Value, so you can either do
value="{{color.name}}"
$scope.thing = {
color: $scope.colors[1].name
}
or
value="{{color}}"
$scope.thing = {
color: JSON.stringify($scope.colors[1])
}
As @bertez mentioned, use ng-value
is the best solution.
ng-value="color"
Have you already tried ng-change directive? You can use a expression to set it checked, try this.
<div ng-app ng-controller="ThingControl">
<ul >
<li ng-repeat="color in colors">
<input type="radio" ng-model="thing.color" value="{{color}}" ng-checked="$index == 0" />{{ color.name }}
</li>
</ul>
Preview: {{ thing }}
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With