How to get checkbox value in angularjs?

Kgn-web picture Kgn-web · Jun 27, 2015 · Viewed 79.5k times · Source

I have a 10(or n)checkbox in my ng-view. Now I would like to ask here that What is the most efficient or simple way to check if checkbox is checked and if checked get the value of checkbox.

I have ng-controller(getAlbumsCtrl), in that I have an array in which I want to push all the checkedbox albums names into albumNameArray

Answer

Icycool picture Icycool · Jun 27, 2015

You can loop over the array to find out which is selected and push into the name array.

<ul>
  <li ng-repeat="album in albums">
    <input type="checkbox" ng-model="album.selected" value={{album.name}} />
  </li>
</ul>

$scope.save = function(){
  $scope.albumNameArray = [];
  angular.forEach($scope.albums, function(album){
    if (!!album.selected) $scope.albumNameArray.push(album.name);
  })
}

// alternatively you can use Array.prototype.filter on newer browsers (IE 9+)
$scope.save = function(){
  $scope.albumNameArray = $scope.albums.filter(function(album){
    return album.selected;
  });
}

jsbin