使用AngularJS的表格中的复选框选择

问题描述:

我想创建一个方法,该方法在检查复选框时从表格中接收一个Id,并更新角度控制器中的$ scope.selected。 并且当复选框未被检查时,它应该再次从$ scope.selected中移除它。使用AngularJS的表格中的复选框选择

到目前为止,它看起来像这样:

$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 }); 
    } 
}; 
+0

而问题是? – 2014-09-24 08:10:17

+0

$ scope.selected(sort_id)!= id(这里有什么正确的语法?) – ShaqCode 2014-09-24 08:14:51

对于在角ckeckboxes互动,我建议使用以下指令: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为您提供工作示例。

+0

非常感谢! 这就像一个魅力! – ShaqCode 2014-09-24 09:19:20

+0

@ShaqCode,欢迎您;)但是如果您有正确的答案,您可以将其标记为最好或有用。谢谢。 – 2014-09-24 09:23:55