2013-03-10 35 views
4

如果這個值是一個對象而不是字符串,我該如何設置收音機的默認值?在ng-repeat中設置收音機的默認值(angular-js)

編輯:

爲了讓事情更清楚,我更新的小提琴: 退房小提琴: 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]; 
}); 

回答

2

檢查在現場HTML瀏覽器控制檯,你會看到oConnection是一個object和收音機的價值變成:{"id":1,"sId":"analog"}。你可能想使用oConnection.id的價值

ng-repeat另外一個問題存在,需要加以解決的ng-model通過設置ng-model$parent.variableName

oConnectionTmpView沒有任何意義,我這麼一個範圍內的繼承問題爲簡化起見,我刪除它:

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" 
    }]; 
} 

演示:http://jsfiddle.net/CrH8a/14/

+0

對不起。 jsfiddle不停地亂搞我....我更新了你的小提琴,告訴你,我試圖達到的目標:http://jsfiddle.net/JohannesJo/PQ7BR/ – 2013-03-11 03:10:36

+0

你是一個天才!如果我將$ scope.oConfigTerminal設置爲1而不是0,它會工作=) – 2013-03-11 03:21:03

+1

這裏有另一種方法...觀察無線電模型並使用它的值來設置您的對象http://jsfiddle.net/PQ7BR/5/ – charlietfl 2013-03-11 03:30:33