Search code examples
javascriptangularjseventsangular-ngmodelbootstrap-switch

Events on model change wont fire


i tried using bootstrap-switch on AngularJS model bound checkbox, but noticed it aint working.

further investigation showed that Javascript onChange/onClick Events are not firing at all when the model change modifies the checkbox. as illustrated in FiddleJS

<input id="cb1" type="checkbox" ng-model="boolValue" /> Changing this wont trigger event on the other Checkbox<br/>

<input id="cb2" type="checkbox" ng-model="boolValue" /> Changing this does trigger the event!

<script>
   $('#cb2').on('change', function(){
       alert('changed');
   });
</script>
  • Why aren't events fire when angular $digest changes the checkbox state?
  • am I doing something wrong here?

Solution

  • The change event fires only when the user interacts with the element:

    Note: Changing the value of an input element using JavaScript, using .val() for example, won't fire the event.

    If you want to execute code when the model changes no matter how, you can set a watch:

    $scope.$watch('boolValue', function(newVal) {
        //...
    });