Angular JS - 按值id选择选项选项

时间:2017-09-18 09:26:28

标签: angularjs select

我对所有用户进行了ng-repeat,但我想要的是他选择了当前用户

    <select id="taskUser" class="form-control"
            multiple="multiple"
            ng-model="taskUser"
            ng-options="user.ID as user.Name for user in header.users"
            >
    </select>

这是我的转发器,我展示了te列表的样子:

<select id="taskUser" class="form-control ng-pristine ng-untouched ng-valid ng-empty" multiple="multiple" ng-model="taskUser" ng-init=" users = header.users[2].id" ng-options="user.ID as user.Name for user in header.users">
    <option label="User 1" value="string:1">User 1</option>
    <option label="User 2" value="string:2">User 2</option>
    <option label="User 3" value="string:3">User 3</option>
</select>

要获取当前用户ID,我使用{{header.user.ID}},而不是获得结果:3

这意味着需要选择

<option label="User 3" value="string:3">User 3</option>

2 个答案:

答案 0 :(得分:1)

$scope.taskUser应该是列表并定义为[3],因为您使用multiple

Fiddle Demo

完整代码:

function MyCtrl($scope, $timeout) {

$scope.header = {
  users:[
  {ID: 1, Name: "AAA"},
  {ID: 2, Name: "BBB"},
  {ID: 3, Name: "CCC"}
  ]
};
$scope.taskUser = [3];   
}

HTML

    <select id="taskUser" class="form-control"
            multiple="multiple"
            ng-model="taskUser"
            ng-options="user.ID as user.Name for user in header.users"
            >
    </select>

    <pre>taskUser: {{taskUser|json}}</pre>

答案 1 :(得分:1)

您需要在数组$scope.taskUser = [3];

中定义所选值

&#13;
&#13;
var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
    $scope.header = {};
    $scope.header.users = [
        { ID: 1, Name: 'John' },
        { ID: 2, Name: 'Rocky' },
        { ID: 3, Name: 'John'},
        { ID: 4, Name: 'Ben' }
    ];
    
    $scope.taskUser = [3];
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
    <fieldset ng-controller="FirstCtrl">
        <select id="taskUser" class="form-control"
            multiple="multiple"
            ng-model="taskUser"
            ng-options="user.ID as user.Name for user in header.users"
            ></select>
    </fieldset>
</div>
&#13;
&#13;
&#13;