Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the checkbox value in angular.js

I have been searching the threads here but can't really find the answer.

I am trying to get the value for the checked boxes when user check 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 my 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 do I do this? Thanks!

like image 898
BonJon Avatar asked Mar 19 '23 03:03

BonJon


1 Answers

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

It's basically sending the event on 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'm considering your controller to be 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);
    }
  }
})

So, you have a list of product objects that have a name and the selected state, you use the checkbox to keep the selected state there, and when you mark/unmark it, the ng-change event is triggered, passing to the add function in the scope the product, you then check the product.name index on the selected_products array, if it's not there, you add it, if it is already there, remove it. This way selected_products matches the selected checkboxes.

like image 175
Rafael Barros Avatar answered Mar 28 '23 07:03

Rafael Barros