Apprentice Programmer
Apprentice Programmer

Reputation: 1515

button to select and deselect all checkboxes not working on

My button that selects all checkboxes in ng-grid works fine. However, i wanted to also implement to deselect with the same button.

here is the original code

app.directive('selectAll',function(){
  return{

    restrict: 'A',
    link: function(scope,element,attr){
     element.click(function() {
     $('.ngViewport.ng-scope input[type="checkbox"]').prop('checked', true);
   });
  }
 };
});

my attempt after doing a bit of googling and basing off other examples:

  app.directive('selectAll',function(){
return{

  restrict: 'A',
  link: function(scope,element,attr){

 element.click(function() {
    if (this.checked) {
     $('.ngViewport.ng-scope input[type="checkbox"]').prop('checked', true);
    }
    else{
    $('.ngViewport.ng-scope input[type="checkbox"]').prop('checked', false);
    }
 });
 }
};
});

for some reason, angular doesn't like the this.checked?? not sure where to go from here.

the plunkr

http://plnkr.co/edit/zy653RrqHmBiRJ7xDHlV?p=preview

Upvotes: 1

Views: 404

Answers (1)

Sushanth --
Sushanth --

Reputation: 55740

You are checking the Checked property of a button.

A button element has no such property.

I would add a class to the button element. And based on that set the checked property for checkboxes. This is using jQuery.

But using Angular you should be avoiding jQuery as a last resort. instead should be using a model to persist the value of the current status.

element.click(function() {
     var $this = $(this),
         isChecked = false;

     if ($this.hasClass('checked')) {
        $this.removeClass('checked');
     } else {
        $this.addClass('checked');
        isChecked = true;
     }
     $('.ngViewport.ng-scope input[type="checkbox"]').prop('checked', isChecked);
});

Check Edited plunker

Upvotes: 1

Related Questions