簡體   English   中英

訪問jquery中的angular2變量

[英]Access angular2 variables in jquery

我在angular2項目中使用jQuery來做一些事情。 但我無法設法使用我在angular2中聲明的變量來在jQuery中使用。 我有這樣的事情:

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 我還可以做些什么?

需要使用的箭頭函數表達式() => {}以保持this范圍。 嘗試:

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);
  });
}

當你通過你的回調是一個普通的舊功能,JavaScript不考慮你的回調是調用函數的范圍內,使this不能用於從范圍調用數據,你以為你是,通過使用箭頭功能,范圍被保存並this是預期訪問數據可用。

如果你想在jquery動畫中使用角度變量動畫ON-Complete函數回調,你就是這樣做的:

$('#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");
  }
});

將此 (實例)的角度分配給Jquery的this (實例)以在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);
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM