Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs: radio button checked

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!

like image 324
Berto Yáñez Avatar asked Aug 29 '13 18:08

Berto Yáñez


2 Answers

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"
like image 110
zs2020 Avatar answered Sep 30 '22 05:09

zs2020


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>
like image 21
andre isaac Avatar answered Sep 30 '22 05:09

andre isaac