hugo der hungrige
hugo der hungrige

Reputation: 12902

Setting the default value for a radio inside of ng-repeat (angular-js)

How can I set a default value for the radios if this value is an object and not a string?

EDIT:

To make things more clear I updated 's fiddle: Check out the fiddle: http://jsfiddle.net/JohannesJo/CrH8a/

<body ng-app="app">
<div ng-controller='controller'>
            oConfigTerminal value= <input type="text" ng-model="oConfigTerminal"/><br><br>

    <div ng-show="!oConnection.aOptions"
    ng-repeat="oConnection in oFormOptions.aStationaryConnections">
        <label>
            <input type="radio" name="connection" ng-model="$parent.oConfigTerminal" value="{{oConnection.id}}"
            />{{oConnection.sId}}</label>
    </div>

</div>

app = angular.module('app', []);

app.controller('controller', function ($scope) {
$scope.oFormOptions = {};
$scope.oConfigTerminal=0;
$scope.oFormOptions.aStationaryConnections = [{
    id: 1,
    sId: "analog"
}, {
    id: 2,
    sId: "isdn"

}, {
    id: 3,
    sId: "dsl"
}];

// !!! Trying to set the default checked/selected value !!!
$scope.oConfigTerminal = $scope.oFormOptions.aStationaryConnections[0];
});

Upvotes: 4

Views: 4571

Answers (1)

charlietfl
charlietfl

Reputation: 171700

Inspect the live html in browser console and you will see that oConnection is an object and value of radio becomes: {"id":1,"sId":"analog"}. You probably want to use oConnection.id for value

One other issue within ng-repeat there is a scope inheritance issue that needs to be resolved for ng-model by setting ng-model to $parent.variableName

Your oConnectionTmpView didn't make any sense to me so for simplification I removed it:

HTML:

<div ng-show="!oConnection.aOptions" ng-repeat="oConnection in oFormOptions.aStationaryConnections">
  <label>
       <input type="radio"  
              name="connection" 
              ng-model="$parent.oConfigTerminal" 
               value="{{oConnection.id}}"
         />
           {{oConnection.sId}}
     </label>
 </div>

JS:

app = angular.module('app', []);

app.controller('controller', function ($scope) {
    $scope.oFormOptions = {};
    $scope.oConfigTerminal = 0;
    $scope.oFormOptions.aStationaryConnections = [{
        id: 1,
        sId: "analog"
    }, {
        id: 2,
        sId: "isdn"

    }, {
        id: 3,
        sId: "dsl"
    }];
}

Demo: http://jsfiddle.net/CrH8a/14/

Upvotes: 2

Related Questions