我正在尝试创建一个方法,当选中复选框时,该方法从表中接收 Id,并且应该更新 Angular Controller 中的 $scope.selected 。 当取消选中该复选框时,它应该再次将其从 $scope.selected 中删除。
到目前为止,它看起来像这样:
$scope.updateselection = function(id) {
if ($scope.selected(sort_id) != id) { //what is the correct syntax here??
$scope.selected.push({ sort_id: id });
} else {
$scope.selected.remove({ sort_id: id });
}
};
最佳答案
为了与 Angular 中的 cckeckbox 交互,我建议使用以下指令:http://vitalets.github.io/checklist-model/
如果您不想使用此指令,您可以在复选框表上创建观察程序。
例如:
HTML:
<table>
<tr>
<td ng-repeat="item in items">
<input type="checkbox" ng-model="item.value">
</td>
</tr>
<table>
JS:
$scope.items = [
{
name: "name1",
value: true
},
{
name: "name2",
value: false
}
];
$scope.selectedItems = [];
$scope.$watch('items', function(newValues){
$scope.selectedItems.length = 0;
angular.forEach(newValues, function(item) {
if (item.value == true) {
$scope.selectedItems.push(item.name);
}
});
console.log($scope.selectedItems);
}, true);
这种方式将允许您始终拥有有关所选复选框的实际信息。
我创建了JSFiddle为您提供工作示例。
关于javascript - 使用 AngularJS 在表中选择复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26011653/