我有一个多选。我有两个不同的数组。我想多选择附带选定的值。
我想从数组中搜索ng-repeat id
如果找到则会变为真,并且值将随选择而来。
我的AngularJS代码
<script>
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.name = "John Brad";
$scope.important_selection = {
"error": false,
"client_data": {
"important": [
{
"id": 10,
"name": "Socially Responsible"
},
{
"id": 8,
"name": "LBGT"
},
{
"id": 4,
"name": "Education"
},
{
"id": 2,
"name": "Retirement"
}
]
},
"status_code": 200
};
$scope.importants_series = {
"error": false,
"important": [
{
"id": 1,
"name": "Investment"
},
{
"id": 2,
"name": "Retirement"
},
{
"id": 3,
"name": "Insurance"
},
{
"id": 4,
"name": "Education"
},
{
"id": 5,
"name": "Tax"
},
{
"id": 6,
"name": "Estate"
},
{
"id": 7,
"name": "Business"
},
{
"id": 8,
"name": "LBGT"
},
{
"id": 9,
"name": "Offshore"
},
{
"id": 10,
"name": "Socially Responsible"
},
{
"id": 11,
"name": "Divorce"
}
],
"status_code": 200
};
});
</script>
我的HTML代码
<select name="important[]" class="form-control" multiple="" required>
<option ng-selected="important_selection.important.find(item => item.id === important.id)" ng-repeat="important in importants_series.important" value="{{important.id}}">{{important.name}}</option>
</select>
现在我想在数组中搜索id,如果为true,那么它将被选中。
我在ng-selected
Plunker Link for more details
:https://plnkr.co/edit/BUnUNqr0IevJ5BkslZNM?p=preview
任何帮助都将表示感谢。
答案 0 :(得分:1)
您应该在ng-options
中使用ng-model
和select
来轻松进行数据绑定。
<select name="important[]" class="form-control" multiple="" required
ng-options="important.name for important in importants_series.important"
ng-model="important_selection.client_data.important"></select>
不幸的是ng-model
只检查对象引用是否相等,所以我们需要额外的步骤来重新分配选择数组本身的数据
var oldArray = $scope.important_selection.client_data.important;
$scope.important_selection.client_data.important = [];
oldArray.forEach(function(item) {
var refItem = $scope.importants_series.important.find(function(i) {
return i.id == item.id;
});
$scope.important_selection.client_data.important.push(refItem);
});
或者您可以将其分配给新阵列。