我使用 ng-repeat
显示 8 个复选框,并通过仅获取选中的值并使用另一个 ng-repeat 将它们显示在逗号分隔的列表中来过滤数据。但是我需要在文本框中显示确切的过滤逗号分隔字符串,并在 ng-repeat 中更新时进行更新。
<div class="col-md-7">
<label class="checkbox" ng-repeat="tooth in teeth">
<input type="checkbox" ng-model="tooth.checked" ng-change="upperRight()" /> {{tooth.id}}
</label>
</div>
<div class="col-md-3">
<span ng-repeat="toothObj in teeth | filter:{ checked: true }">{{toothObj.id}}{{$last ? '' : ', '}}</span>
<input type="text" ng-model="selectedTeeth" />
</div>
控制器
$scope.teeth = [
{ id: 1, checked: false },
{ id: 2, checked: false },
{ id: 3, checked: false },
{ id: 4, checked: false },
{ id: 5, checked: false },
{ id: 6, checked: false },
{ id: 7, checked: false },
{ id: 8, checked: false }
];
在这里,我将其添加到 plunker 中,以便更好地理解 Plunker URL
我只是按照以下方式做到的
我的控制器
$scope.teethUR = [{ id: 1, checked: false }, { id: 2, checked: false }, { id: 3, checked: false }, { id: 4, checked: false }, { id: 5, checked: false }, { id: 6, checked: false }, { id: 7, checked: false }, { id: 8, checked: false }];
$scope.upperRight = function () {
$scope.URSelected = "";
for (var i = 0; i < $scope.teethUR.length; i++) {
if ($scope.teethUR[i].checked == true) {
if ($scope.URSelected == "") {
$scope.URSelected = $scope.teethUR[i].id;
} else {
$scope.URSelected = $scope.URSelected + ", " + $scope.teethUR[i].id;
}
}
}
}
和网页
<div class="col-md-7">
<label class="checkbox" ng-repeat="tooth in teethUR">
<input type="checkbox" ng-model="tooth.checked" ng-change="upperRight()" /> {{tooth.id}}
</label>
</div>
<div class="col-md-3">
<input type="text" ng-model="URSelected" class="form-control" />
</div>
看看这里的工作代码 普朗克演示
演示
可以在文本框和复选框之间设置双向绑定。单击
复选框时,文本框将更新,更新文本框时,复选框将更新。首先,设置两个手表:一个监视牙齿,另一个监视 selectedTooth:
$scope.$watch ('teeth', function(newVal) {
$scope.selectedTeeth = [];
for(var i = 0; i < newVal.length; ++i) {
if (newVal[i].checked)
$scope.selectedTeeth.push(newVal[i].id);
}
}, true);
$scope.$watch('selectedTeeth', function(newVal) {
for (var j = 0; j < $scope.teeth.length; ++j) {
var tooth = $scope.teeth[j];
if (newVal.indexOf(tooth.id) >= 0) {
tooth.checked = true;
}
else {
tooth.checked = false;
}
}
}, true);
接下来设置一个 ngModel 指令,它提供了一个格式化程序和一个解析器来封送"牙齿"和"选定牙齿",反之亦然:
app.directive ('teethTextBox', function() {
return {
restrict: 'A',
require: 'ngModel',
scope: { ngModel: '=' },
link:function(scope, element, attr, ngModelController) {
ngModelController.$formatters.push(function(value) {
return value;
});
ngModelController.$parsers.push(function(value) {
var numbers = [];
var tmp = value.split(',');
for (var i = 0; i < tmp.length; ++i) {
numbers.push(parseInt(tmp[i]))
}
return numbers;
});
}
}
});
在 HTML 中挂接指令:
<body ng-controller="MainCtrl">
<div class="col-md-7">
<label class="checkbox" ng-repeat="tooth in teeth">
<input type="checkbox" ng-model="tooth.checked" ng-change="upperRight()" /> {{tooth.id}}
</label>
</div>
<div class="col-md-3">
<input type="text" ng-model="selectedTeeth" teeth-text-box />
</div>
</body>