gpt4 book ai didi

javascript - 使用 ng-model 和 ng-repeat 进行多个默认选择

转载 作者:行者123 更新时间:2023-12-03 04:38:03 25 4
gpt4 key购买 nike

<script src="" https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js ""></script>
<script>
var app = angular.module('role', []);

app.controller('fooController', function($scope) {
$scope.roles = [{
id: 1,
name: "Administrator"
}, {
id: 2,
name: "Student"
}, {
id: 3,
name: 'worker'
}];
$scope.user = {};
$scope.value=function(){
$scope.user = [name:'abc',roles:[{
id: 2,
name: 'Student'
}, {
id: 3,
name: 'worker'
}];
}
});
</script>

<body>
<button type="button" ng-click="value()">Click me </button>
<form ng-repeat="test in user">
<input type="text" ng-model="test.name">
<select multiple class="form-control" data-ng-model="user.roles" required>
<option ng-repeat="role in roles" value="{{role.id}}">{{role.name}}</option>
</select>
</body>

我想通过默认值与 ng-model 绑定(bind)选择值,默认情况下我只想使用 ng-repeat 而不是 ng-options 它应该选择 $scope.user.roles 值中的值

最佳答案

这个怎么样?

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('role1', []);

app.controller('fooController', function($scope) {
$scope.roles = [{
id: 1,
name: "Administrator"
}, {
id: 2,
name: "Student"
}, {
id: 3,
name: 'worker'
}];
$scope.user = {};

$scope.user.roles = [{
id: 2,
name: 'Student'
}, {
id: 3,
name: 'worker'
}];
$scope.user.roles.id = $scope.user.roles.map(function(a) {
return a.id;
});
});
</script>

<body ng-app="role1" ng-controller="fooController">
<select multiple class="form-control" data-ng-value="user.roles" required>
<option ng-repeat="role in roles" ng-selected="user.roles.id.indexOf(role.id) != -1" value="{{role.id}}">{{role.name}}</option>
</select>
</body>

关于javascript - 使用 ng-model 和 ng-repeat 进行多个默认选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43205163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com