访问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
无法从你认为你所在的范围调用数据。通过使用Arrow函数,可以保存作用域,并且this
可以用于访问预期的数据。
如果你想在jquery中使用angular变量animate 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");
}
});
将angular的this(instance)赋值给Jquery的this(instance)以使用Jquery内部的angular变量
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);
});
相关文章:
- 将函数的上下文应用于javascript变量
- 无法导出函数expressjs/requestjs中的变量
- 函数参数中的数据与指定变量之间的任何性能差异
- Angular2/JavaScript-如何显示localStorage保存的所有变量并获取所有键的总长度
- angular2中的全局变量,其值可以更改
- Angular2/Typescript:从链接可观察函数访问实例变量
- 为什么我们将“(keyup)”分配给模板局部变量的随机值以在 Angular2 中更新
- Angular2:如何在输入元素上动态设置数据绑定变量
- Angular2 - 组件变量/组件类属性上的双向数据绑定
- Angular2 火力基地检索并分配变量
- Angular2,视图在settimeout变量更改后未更新
- Angular2的ngModel和ngFor变量
- 访问jquery中的angular2变量
- Angular2在组件之间传递变量
- 如何在Angular2中触发一个应用范围的事件或者观察一个全局变量?
- Angular1的作用域变量在angular2
- 如何访问或更新其他组件类angular2中的组件类变量
- Angular2 (RC5)中应用范围的变量
- JavaScript ES6对Angular2的承诺——未定义的变量
- Angular2变量'Undefined'外部方法