Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Bootstrap 3 javascript checkbox and radio button toggle prevents angular's ng-model from updating on input #4516

Closed

Description

@pholly

When using Bootstrap 3's javascript buttons for checkboxes, the checkbox's ng-model does not get updated. Looking into the source code for both I know why.

Bootstrap 3 html for checkbox button group:

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary">
    <input type="checkbox"> Option 1
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> Option 2
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> Option 3
  </label>
</div>

Bootstrap 3 javascript for button toggle:

Button.prototype.toggle = function () {
        var $parent = this.$element.closest('[data-toggle="buttons"]')

        if ($parent.length) {
            var $input = this.$element.find('input')
              .prop('checked', !this.$element.hasClass('active'))
              .trigger('change')
            if ($input.prop('type') === 'radio') $parent.find('.active').removeClass('active')
        }

        this.$element.toggleClass('active')
    }

Angular source for checkbox (radio button is similar):

function checkboxInputType(scope, element, attr, ctrl) {
        var trueValue = attr.ngTrueValue,
            falseValue = attr.ngFalseValue;

        if (!isString(trueValue)) trueValue = true;
        if (!isString(falseValue)) falseValue = false;

        element.on('click', function () {
            scope.$apply(function () {
                ctrl.$setViewValue(element[0].checked);
            });
        });

        ctrl.$render = function () {
            element[0].checked = ctrl.$viewValue;
        };

        ctrl.$formatters.push(function (value) {
            return value === trueValue;
        });

        ctrl.$parsers.push(function (value) {
            return value ? trueValue : falseValue;
        });
    }

The problem is Angular's checkbox is listening for the click event whereas Bootstrap's button handles the click event and fires the change event on the checkbox input.

I wrote a simple directive that does exactly what Angular's checkbox click event listener does but instead listens for the change event.

appModule.directive('mccCheckboxDetectChange', [function mccCheckboxDetectChange() {

    return {
        replace: false,
        require: 'ngModel',
        scope: false,
        link: function (scope, element, attrs, ngModelCtrl) {
            element.on('change', function () {
                scope.$apply(function () {
                    ngModelCtrl.$setViewValue(element[0].checked);
                });
            });
        }
    };
}]);

Is there a reason why Angular listens for the click event for radio and checkboxes instead of the change event? Should I create a pull request and change the click event listener to be a change event listener? This would be my first pull request.

Thanks!
Philip

Activity

  1. stevschmid commented on Jan 22, 2014

    @stevschmid

    I ran into the same issue.

  2. caitp commented on Jan 22, 2014

    @caitp
    Contributor

    Could you guys post a really minimal reproduction? If it's something like pointer-events: none or something then I'm not sure what we can really do about that

  3. stevschmid commented on Jan 24, 2014

    @stevschmid
  4. caitp commented on Jan 24, 2014

    @caitp
    Contributor

    I see what's happening. So, I'm not sure if it would be right to handle this in angular core, this seems like it's more the domain of custom directives for interop with bootstrap. So writing your own is one thing, or otherwise hacking on n angular-strap or angular-ui/bootstrap or others.

    But I'll see what people think about it

  5. stevschmid commented on Jan 25, 2014

    @stevschmid

    Why is angular listening for click events instead of change events for both radio buttons and check boxes?

  6. danse commented on Feb 24, 2014

    @danse

    👍

  7. ericpeters0n commented on Mar 17, 2014

    @ericpeters0n

    +1

  8. david-hollifield commented on Mar 26, 2014

    @david-hollifield

    +1

  9. bimusiek commented on Mar 27, 2014

    @bimusiek

    👍

  10. david-hollifield commented on Mar 27, 2014

    @david-hollifield

    To anyone that's interested, pholly's directive fixed the issue I was having with my radio buttons (with a minor tweak).

            return {
                replace: false,
                require: 'ngModel',
                scope: false,
                link: function (scope, element, attrs, ngModelCtrl) {
                    element.on('change', function () {
                        scope.$apply(function () {
                            ngModelCtrl.$setViewValue(element[0].type.toLowerCase() == 'radio' ? element[0].value : element[0].checked);
                        });
                    });
                }
            };
    
  11. fgmacedo commented on Jun 27, 2014

    @fgmacedo

    +1

  12. 8 remaining items

  13. glorat commented on Oct 9, 2014

    @glorat

    +1 and much gratitude for people here posting the workaround

  14. claudijo commented on Dec 10, 2014

    @claudijo

    Thanks for posting a workaround for checkboxed toggle buttons that works reasonably well. However, as one of the referenced issues suggests, it seems like the workaround as mentioned by pholly, will require two clicks for the initial toggle if the checkbox is checked by default. See http://jsfiddle.net/6admtjf1/1/ (I forked stevschmid's fiddle, added ng-checked="true" to the checkbox, and removed bootstrap css to emphasize what is going on "behind the curtain").

    Any ideas how to work around the workaround, to make this work as expected even if the default state for the button is checked?

  15. ppryde commented on Feb 16, 2015

    @ppryde

    +1

  16. heridev commented on Oct 14, 2015

    @heridev

    In order to support default checked checkboxes I ended up using

    
       .directive('checkboxWithChangeHandler', ['$timeout', function($timeout) {
         return {
           replace: false,
           require: 'ngModel',
           scope: false,
           link: function (scope, element, attr, ngModelCtrl) {
            $timeout( function(){
              if(element[0].checked) {
                $(element).parent().addClass('active')
              }
            }, 0);
    
             $(element).change(function () {
               scope.$apply(function () {
                 ngModelCtrl.$setViewValue(element[0].checked);
               });
             });
           }
         };
       }]);
    

    Is there a better way to support pre-selected checkboxes?

  17. ERobishaw commented on Nov 5, 2015

    @ERobishaw
  18. Fleisch commented on Dec 15, 2015

    @Fleisch

    +1 .... @ERobishaw thank you.. instantly worked

  19. added 2 commits that reference this issue on May 27, 2016
    ee23d70
    ee24a68
  20. added a commit that references this issue on Mar 29, 2017
    e1b9f59
  21. added 4 commits that reference this issue on Oct 6, 2017
    3ae9cba
    8d5b9ba
    c9c7d7c
    f460088
  22. added a commit that references this issue on Oct 13, 2017
    656c8fa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions