简体   繁体   English

按钮以选择和取消选择所有不起作用的复选框

[英]button to select and deselect all checkboxes not working on

My button that selects all checkboxes in ng-grid works fine. 我的按钮可以选中ng-grid中的所有复选框。 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?? 由于某种原因,Angular不喜欢this.checked? not sure where to go from here. 不知道从这里去哪里。

the plunkr 朋克

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

You are checking the Checked property of a button. 您正在检查按钮的Checked属性。

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. 然后基于此设置复选框的checked属性。 This is using jQuery. 这是使用jQuery。

But using Angular you should be avoiding jQuery as a last resort. 但是使用Angular应该避免使用jQuery作为最后的手段。 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 检查编辑的punker

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM