javascript - 使用 AngularJS 在表中选择复选框

标签 javascript angularjs angularjs-scope

我正在尝试创建一个方法,当选中复选框时,该方法从表中接收 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/

相关文章:

javascript - AngularJS : Scope access between directives and transcluded directives

javascript - 如何在javascript中创建一个仅包含特定位置元素的数组?

javascript - 显示从数据库中检索到的图像(C# 和 JS)

javascript - 如何使用jquery获取第n个子值

javascript - 使用指令会导致字段变灰,但字段仍然有效

forms - 如何滚动到表单中的错误?

javascript - 追加时节点从循环中消失

javascript - $scope.$on ('$routeChangeSuccess' ...) 和调用作用域函数中的方法有什么区别?

angularjs - 如何等待 Protractor 端的http请求响应

angularjs - 在 Jasmine 测试中获取自定义指令的 Controller 范围