How to get checkbox value in angular.js

I searched for topics here, but cannot find the answer.

I am trying to get the value for checked boxes when the user checks them in Angular. I have something like

<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>

I want to have something in js like

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

How should I do it? Thank!

+4
source share
2 answers

The angular solution can be seen here: http://plnkr.co/edit/j63po37JBvc3bFdNAl3T

It basically sends an event to 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>

and I view your controller like this:

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, , product.name selected_products, , , , . , selected_products .

+5

ng-model = "product.selected" HTML

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

selectedProducts $scope, - , , $ - ...

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.
};
+2

Source: https://habr.com/ru/post/1546934/


All Articles