2016-09-28 3 views
4

내 angular2 프로젝트에서 일부 항목에 대해 jQuery를 사용하고 있습니다. 하지만 angular2에서 선언 한 변수를 jQuery에서 사용할 수는 없습니다. 나는 다음과 같은 것을 가지고있다 :jQuery에서 angular2 변수에 액세스

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을 사용하기 때문에 그것이라고 생각합니다. 그 밖의 무엇을 할 수 있습니까?

+0

내가 Angular2를 사용하지 않지만 같은 범위에 변수를 추가 할 수 있습니다 결코 각도 1에? – manuerumx

+0

저는 Angular2를 1 주일 동안 사용하고 있습니다. 확실하지는 않지만 v2에 스코프와 같은 것이 있다고 생각하지 않습니다. – user2529173

+0

[Javascript : "this"변수를 쉽게 설정하는 방법?] http://stackoverflow.com/questions/456967/javascript-how-to-set-this-variable-easily) –

답변

13

범위 모양을 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); 
    }); 
} 

는 자바 스크립트 호출 함수의 범위에 포함되는 콜백을 고려하지 않는 범위에서 데이터를 호출 사용할 수 없게 this를 떠나 당신은 당신이 생각했다 화살표 기능을 사용하면 범위가 저장되고 예상대로 데이터에 액세스하는 데 this을 사용할 수 있습니다.

+1

예, 그랬어요! 감사! – user2529173

0

는 ON-전체 함수 호출 다시 JQuery와 애니메이션에서 각 변수를 사용하고자하는 경우, 그건 당신이 그것을 할 방법 :

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