Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access angular2 variables in jquery

I'm using jQuery for some things in my angular2 projects. But I can't manage to use variables I've declared in angular2 to use in jQuery. I have something like this:

export class AddExerciseComponent implements OnInit {

  parameters:Array<string> = ["FU"];

  constructor() { }

  ngOnInit() {


    $('.chips').on('chip.add', function(e, chip){
      this.parameters.push(chip.data);
      console.log(this.selectedValue);
    });
}

This would get me an error that parameters is not defined. I guess it's because I use this. What else can I do?

like image 931
user2529173 Avatar asked Sep 28 '16 16:09

user2529173


3 Answers

You need to use an arrow function expression (() => {}) to keep this in scope. Try:

export class AddExerciseComponent implements OnInit {

parameters:Array<string> = ["FU"];

constructor() { }

ngOnInit() {
// removed function keyword and added () => {} syntax
  $('.chips').on('chip.add', (e, chip) => {  
    this.parameters.push(chip.data);
    console.log(this.selectedValue);
  });
}

When you passed your callback as a regular old function, JavaScript doesn't consider your callback to be within the scope of the calling function, leaving this unusable for calling data from the scope you thought you were in. By using an Arrow function, the scope is saved and this is usable for accessing data as expected.

like image 81
gelliott181 Avatar answered Oct 07 '22 01:10

gelliott181


If you are looking to use angular variables in jquery animate ON-Complete function call back,that's how you do it:

$('#myDiv').animate({top: 70+"%"},{

  queue: false,
  duration: 1000,
  complete: () => {  

  //this is you angular variable of the class
      this.angularVar = 0;
      $("#myDiv").hide();

  //this is you angular variable of the class    
      this.showAnimation = false;

  //this is you angular class function
      this.angularFunction();

      console.log("animation complete");
  }
});
like image 30
Asad Avatar answered Oct 07 '22 00:10

Asad


Assign angular's this(instance) to Jquery's this(instance) to use the angular variable inside JQuery

let jQueryInstance = this; // This line will assign all the angular instances to jQueryInstance variable.
$('.chips').on('chip.add', (e, chip) => { 

    /* this.parameters.push(chip.data); */

    // Instead of the above line we have to use like below
    jQueryInstance.parameters.push(chip.data); // instead of "this", "jQueryInstance" is used

    // console.log(this.selectedValue);
    console.log(jQueryInstance.selectedValue);
  });
like image 45
Pravinraj Venkatachalam Avatar answered Oct 07 '22 00:10

Pravinraj Venkatachalam