javascript - Angular 遍历选择选项并设置选定值

标签 javascript angularjs

我有一个来自 JSON 数据的状态选择集:

<select name="ParentState" ng-model="selectedState" ng-options="s.StateID as s.StateCode for s in cStates | orderBy:'StateCode'">
    <option value="">Select State...</option>
</select>

并想将选定状态设置为为登录用户返回的状态,但我完全确定如何在 Angular 中完成此操作。这是我尝试过的方法,但没有用。

angular.forEach($scope.cState, function (s) {
    if (s.StateCode == xParentState) {
        $scope.selectedState = s.StateCode;
    }
});

xParent 是这个状态的首字母,例如'MI' 代表密歇根

最佳答案

ngModel 设置为 StateID(如您的 ngOptions 所示 - value as text for object in array) - 所以设置它而不是 StateCode

if (s.StateCode == xParentState) {
    $scope.selectedState = s.StateID;
}

关于javascript - Angular 遍历选择选项并设置选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31121852/

相关文章:

javascript - 当他们的任何一个 child 被取消选择时如何取消选中所有复选框

javascript - 为什么 call.call 调用函数

javascript - Yii2:将变量从 Controller 传递给javascript

javascript - Angular 将数据从 Controller 传递到状态

javascript - jsp中iframe加载问题

javascript - 当 session 下拉字段选择的文本是管理员时,jQuery 验证不会触发所需的条件?

javascript - AngularJS 使用 UI Router 进行翻译

Angularjs - 多个 $http REST 调用(第二个调用取决于第一个的输出)

angularjs - Spring MultipartException : The current request is not a multipart request

javascript - Angular JS 中带有 Ng-Include 的未定义函数