簡體   English   中英

如何獲取angular.js中的復選框值

[英]How to get the checkbox value in angular.js

我一直在搜索這里的主題,但無法找到答案。

當用戶在Angular中檢查它時,我試圖獲取復選框的值。 我有類似的東西

<div class="checkbox">

<div class="checkbox" ng-repeat="product in products">
    <input type="checkbox" ng-model="product"/> {{product.name}}
</div>

<button ng-click='add()'></button>

我希望在我的js中有一些東西

$scope.add = function() {
    //I want to add the checked product in the selectedProduct array
    $scope.selectedProduct = ['product1', 'product2', 'product4']  => the selected products.
}

我該怎么做呢? 謝謝!

角度解決方案可以在這里看到: http//plnkr.co/edit/j63po37JBvc3bFdNAl3T

它基本上是在ng-change上發送事件

<div class="checkbox" ng-repeat="product in products">
    <input type="checkbox" ng-model="product.selected" ng-change="add(product)"/> {{product.name}}<br>
</div>

而我正在考慮你的控制器是這樣的:

app.controller('myController', function($scope){
  $scope.products = [
    {'name':'product1', 'selected': false},
    {'name':'product2', 'selected': false},
    {'name':'product4', 'selected': false}
  ];
  $scope.selected_products = [];

  $scope.add = function(prod){
    var index = $scope.selected_products.indexOf(prod.name);
    if(index == -1 && prod.selected){
      $scope.selected_products.push(prod.name);
    } else if (!prod.selected && index != -1){
      $scope.selected_products.splice(index, 1);
    }
  }
})

因此,您有一個具有名稱和所選狀態的產品對象列表,您可以使用復選框將選定狀態保留在那里,當您標記/取消標記它時,觸發ng-change事件,傳遞給add函數在產品范圍內,然后檢查selected_products數組上的product.name索引,如果它不存在,則添加它,如果它已經存在,則將其刪除。 這種方式selected_products匹配選定的復選框。

在HTML中使用ng-model =“product.selected”

<div class="checkbox" ng-repeat="product in products">
  <label><input type="checkbox" ng-model="product.selected"/> {{product.name}}</label>
</div>

在你的添加功能中,你不需要在你的$scope上保留selectedProducts ,除非你想在你的視圖中顯示它,或者可能因為某些原因$ watch觀看它...

我建議只需構建該數組,並在需要時在add()函數的閉包中使用它。

JS(適用於所有瀏覽器)

$scope.add = function(){
  var selectedProducts = [];
  angular.forEach($scope.products, function(product) {
    if(product.selected) selectedProducts.push(product);
  });

  // TODO: do something with selectedProducts here
};

JS使用Array.prototype.filter(如果IE8不是問題)

$scope.add = function(){
  var selectedProducts = $scope.products.filter(function(product) {
    return product.selected;
  });

  // TODO: do something with selectedProducts.
};

暫無
暫無

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

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