所以我有一个选择集,我想默认为登录用户的状态。返回的状态JSON是StateCode
,例如"MI"
<div>
<select
name="ParentState"
ng-model="selectedState"
ng-options="s.StateCode for s in cStates track by s.StateID | orderBy:'StateCode'">
</select>
</div>
并在我的控制器中
var init = function() {
angular.forEach(xStates, function(xS) {
if (xS.StateCode == xParentState) {
$scope.selectedState = xS.StateID;
$scope.vName = "It's working!" + $scope.selectedState;
}
});
}
init();
init函数的最后一行只写到{{ vName }}
,这样我就可以看到函数正常工作,$scope.selectedState
的值是正确的,例如"MI"
将是{ {1}}但是加载页面时的选择未设置为23
。
答案 0 :(得分:1)
我认为这里可能会出现一些问题,而且我对你想要的结果采取了一些最好的猜测。首先,标记中的s.StateCode for s...
将使用<option>
填充StateCode
。你提到你希望看到"MI"
,所以让我们将其改为StateName
。其次,默认$scope.selectedState
作为我们的模型,不需要指定StateId
- 只需选择对象,AngularJS将满足默认我们的ng-options
。这是一个完整的例子,对我的想法有一些解释。
<select
name="ParentState"
ng-model="selectedState"
ng-options="s.StateName for s in xStates track by s.StateID | orderBy:'StateCode'">
app.controller('ctrl', ['$scope', function($scope) {
$scope.xStates = [{'StateCode': 1, 'StateID': 'A', 'StateName': 'AL'},
{'StateCode': 23, 'StateID': 'B', 'StateName': 'MI'},
{'StateCode': 50, 'StateID': 'C', 'StateName': 'Hawaii'}];
angular.forEach($scope.xStates, function (xS) {
if (xS.StateCode === 23) { // -- for demo simplicity
$scope.selectedState = xS;
}
});
}]);
JSFiddle Link - 工作演示