Search code examples
javascripthtmlangularicheck

Losing variable value assigned in iCheck callback in Angular


I'm new at this so be kind.

I've got these 2 functions inside the same component.ts

First one:

addCost() {
    $(document).ready(function(){
                    (<any>$('input')).iCheck({
                        checkboxClass: 'icheckbox_square-blue',
                        radioClass: 'iradio_minimal-grey'
                    });
                    $('#not2bpaid').on('ifChecked', () => {
                        this.not2bpaid_tosend = "N";
                    });
}

This variable assignment in 'ifChecked' callback works, I've made sure of that.

And then I have another function which is called on click event in html which uses the variable not2bpaid_tosend.

addCost() is called BEFORE the function at click event, but by then not2bpaid_tosend has lost its value.

I've also tried passing not2bpaid_tosend as a parameter to the 2nd function upon triggering it from html. Same result. Variable is empty by then. And I'm not touching that variable at any other time between those 2 functions.

Not sure what's going on here or how to solve it. Probably something simple that I overlooked since, as I said, I'm new at this angular stuff.

Any help would be appreciated. thanks


Solution

  • You have to use arrow function while passing function an argument to the ready function of jquery to keep the context of component class intact.

    addCost() {
      $(document).ready(() => {
        (<any>$('input')).iCheck({
          checkboxClass: 'icheckbox_square-blue',
          radioClass: 'iradio_minimal-grey'
        });
        $('#not2bpaid').on('ifChecked', () => {
          this.not2bpaid_tosend = "N";
        });
      });
    }