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

时间:2018-04-09 04:41:25

标签: javascript angularjs

我对AngularJS相当新,我在这里已经阅读了一些答案,但没有成功。我有一个控制器的json文件,我在select中显示。我想根据文本值设置所选值。这是我到目前为止所做的。

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>        

控制器:

<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>

或者有关如何执行此操作的任何其他建议?

1 个答案:

答案 0 :(得分:0)

问题是您没有将模型映射到您拥有的数组中的任何元素。 假设您拥有要选择的用户的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));
    }

另请注意,您可以选择第一个:

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