我有一个简单的代码,列出了很多颜色,并检查用户是否选择了某些颜色(这是在代码上设置的,但实际上它来自数据库)。当我提交表单时,未检查的输入未在数组中列出,如果我取消选中某些输入,则不会从数组中删除它。
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>
请勿同时使用ng-model
和ng-checked
。使用ng-model
进行双向绑定,使用ng-checked
进行单向绑定。
<ul>
<li ng-repeat="color in colors">
<input
type="checkbox"
name="{{color}}"
id="{{color}}"
̶n̶g̶-̶c̶h̶e̶c̶k̶e̶d̶=̶"̶i̶s̶U̶s̶e̶r̶C̶o̶l̶o̶r̶(̶c̶o̶l̶o̶r̶)̶"̶
ng-model="user.colors[$index]"
̶v̶a̶l̶u̶e̶=̶"̶{̶{̶c̶o̶l̶o̶r̶}̶}̶"̶
>
<label for="{{color}}">{{color}}</label>
</li>
</ul>
代替从控制器初始化模型:
$scope.user = { colors: [] };
$scope.user.colors = $scope.colors.map(c => $scope.preChecked.some(_ => _ == c));