简体   繁体   English

如何在ng-select或ng-options中设置默认的选定文本?

[英]How to set default selected text in ng-select or ng-options?

I am fairly new to AngularJS and I have been reading some answers here but nothing worked out. 我是AngularJS的新手,我在这里阅读了一些答案,但没有解决。 I have a json file from a controller that I display in a select. 我在选择中显示了来自控制器的json文件。 I want to set the selected value based on the text value.This is what I have so far. 我想基于文本值设置选定的值。这是我到目前为止的结果。

HTML: HTML:

<div ng-app="userModule" ng-controller="userCtrl">
<div class="row">
    <div class="col-md-6">
        <label>User Name:</label> <br />
        <select ng-model="users.selectedUser" class="form-control" ng-options="item.UserName as item.UserName for item in users.availableOptions"></select>
    </div>        

Controller: 控制器:

<script>
var _$http;
var _$scope;
var oldUser = @Html.Raw(Json.Serialize(ViewData["UserName"]));
var oldRole = @Html.Raw(Json.Serialize(ViewData["RoleName"]));
angular.module('userModule', [])
    .controller('userCtrl', xConstructor);

function xConstructor($scope, $http) {
    _$http = $http;
    _$scope = $scope;
    $http.get("/RoleManagement/GetUserData").then(xReceive);
    $http.get("/RoleManagement/GetRoleData").then(roleReceive);

    _$scope.submit = function () {
        //alert("Here:" + _$scope.selectedUser);
        $http.get("/RoleManagement/PutUserRoleData?UserId=" + _$scope.selectedUser.UserId + "&RoleId=" + _$scope.selectedRole.RoleId).then(writeSuccess);
    }

}

function xReceive(userObject) {
    _$scope.users = {
        availableOptions: userObject.data,
        **selectedUser: { UserId: oldId, UserName: oldUser } //What to put here?**
    };

    alert(JSON.stringify(JSON.stringify(_$scope.users.selectedUser));
}
</script>

Or any other suggestions on how to do this? 或关于如何执行此操作的任何其他建议?

The problem is you are not mapping the model to any element in the array you have. 问题是您没有将模型映射到数组中的任何元素。 Assuming you have the id of the user you want to select this is what you do: 假设您具有要选择的用户的ID,这就是您要做的:

 function xReceive(userObject) {
        _$scope.users = {
            availableOptions: userObject.data,
            selectedUser: null
        };

        let selectedUser;
        for (let i = 0; i < userObject.data.length; i++) {
          if (userObject.data[i].id === oldId) {
           selectedUser = userObject.data[i];
           break;
          }
        }
        if (selectedUser) {
          _$scope.users.selectedUser = selectedUser;
        }
        alert(JSON.stringify(JSON.stringify(_$scope.users.selectedUser));
    }

Also note, you can do this to just select the first one: 另请注意,您可以执行以下操作以仅选择第一个:

_$scope.users.selectedUser = _$scope.users.availableOptions[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM