簡體   English   中英

AngularJS:跟蹤選中的復選框

[英]AngularJS: tracking which checkbox is checked

在HTML表單中,我需要跟蹤檢查哪些復選框,以便將其插入到要發布到后端的查詢對象中。

我在$ scope中的數組中有以下三個復選框:

$scope.typeCheckBoxes = [
      {label: "A", val: true},
      {label: "B", val: false},
      {label: "C", val: false}
    ];

以下是我在表單中呈現復選框的模板:

<span ng-repeat="chk in typeCheckBoxes">
<input type="checkbox" ng-model="chk.val" id="chk.label" ng-change="addType(this)" />
            <label>{{chk.label}}</label>
</span>

在我的控制器中,我嘗試創建函數addType()以將選中的復選框添加到我的查詢對象:

$scope.queryObj = {
types: []
};

$scope.addType = function(e) {
   var selectedBox = angular.element(e.id); // not working
   if (selectedBox) {
     $scope.queryObj.types.push(selectedBox);
   }

};

但是,我不確定如何獲取已選中復選框的id 非常感謝你的幫助。

您可以在控制器中執行此操作:

$scope.$watch('typeCheckBoxes', function(newObject, oldObject) {
// You can do what you want with your newObject here
}, true);

不要忘記true作為第二個參數。 這允許您觀看整個對象而不僅僅是一個簡單的值。 這個$ watch將在每次更改時觸發。

因為復選框的ID是標簽,所以你也可以在newObject中使用它。

你要丟失的第一件事是,你應該在范圍內編寫addType函數,以便在更改復選框時觸發它(因為你使用ng-change指令來查找當前范圍內的函數)你可以在你的內部獲得ng-change事件控制器並在對象上執行簡單的forEach。

$scope.addType = function(){
   angular.forEach($scope.typeCheckBoxes, function(value, index) {
      if(value.val)
       console.log('value.id');//here you can get selected value
   });
}

更新:

實際上,您可以通過使用Angular $filter服務來過濾數組並獲取已檢查和未選中的列表,從而獲得所需的已檢查/未檢查標簽列表。 然后為了獲得標簽,你需要做一個for循環。

 $scope.$watch('typeCheckBoxes', function (newObj, oldObj) {
   var types, 
   checked = $filter('filter')(newObj, {'val': true}), //checked list
   unchecked = $filter('filter')(newObj, {'val': false}); //unchecked list
   console.log(checked);
   console.log(unchecked);
   for (var i=0; i< checked.length; i++) {
      types.push(checked[i].label); //adding checked labels to type array 
   }
}, true);

工作小提琴

這對你有所幫助,謝謝。

@jlouazel的建議啟發,我對$scope.$watch()方法進行了一些研究,在我看來,它更像是Angular 所以我提出了以下解決方案,該方案有效但缺乏直接獲取復選框的靈活性。 我必須使用for循環來檢查復選框組中的哪個復選框被選中/取消選中。

$scope.$watch('typeCheckBoxes | filter: {val: true}', function(newObj, oldObj) {

    // checked ones
    for (var props in newObj) {
      console.log(newObj[props].label);
      types.push(newObj[props].label); //save the checked label
    }

    //unchecked ones
    for (var props in oldObj) {
      console.log('oldObj[' + props + '] =' + oldObj[props].label);
      types.splice(types.indexOf(oldObj[props].label, 1); // remove the unchecked label
    }
  }, true);

使用for循環查找選中的復選框真的很麻煩。 因此,我需要改進( 如果可能的話 )上面的代碼來直接獲取已檢查的代碼而不是使用循環。 任何建議將不勝感激。

謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM