我有一个简单的代码,列出了许多颜色,并检查用户是否预先选择了一些颜色(这是在代码上设置的,但实际上它来自数据库)。当我提交表单时,预先检查的输入不会列在数组中,如果我取消选中一些,这不会从数组中删除。
const SampleApp = angular.module('SampleApp', [])
SampleApp.controller('sampleAppController', function($scope) {
$scope.colors = ['red', 'green', 'blue', 'black', 'yellow', 'pink', 'white']
$scope.preChecked = ['green', 'pink']
$scope.user = { colors: [] }
$scope.colorArr = []
$scope.isUserColor = color => {
return $scope.preChecked.some(uColor => color === uColor)
}
$scope.handleSubmit = () => {
const filteredColors = $scope.colors.filter((color, index) => {
return $scope.user.colors.some((uColor, uIndex) => {
return index === uIndex
})
})
$scope.colorArr = filteredColors
}
})
<html lang="en" ng-app="SampleApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
</head>
<div ng-controller="sampleAppController">
<form ng-submit="handleSubmit()">
<ul>
<li ng-repeat="color in colors">
<input
type="checkbox"
name="{{color}}"
id="{{color}}"
ng-checked="isUserColor(color)"
ng-model="user.colors[$index]"
value="{{color}}"
>
<label for="{{color}}">{{color}}</label>
</li>
</ul>
<button>Submit</button>
</form>
<div>{{colorArr}}</div>
</div>
</body>
</html>