在jQuery中访问Angular2变量 [英] Access angular2 variables in jquery

查看:80
本文介绍了在jQuery中访问Angular2变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的angular2项目中,我正在使用jQuery做某些事情.但是我无法使用在angular2中声明的变量在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.我还能做什么?

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

推荐答案

您需要使用箭头函数表达式(() => {})将this保留在范围内.试试:

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

当您将回调作为常规的旧函数传递时,JavaScript不会将您的回调视为在调用函数的范围之内,从而使this无法用于从您认为所在的范围中调用数据.箭头功能,将保存作用域,并且this可用于按预期访问数据.

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.

这篇关于在jQuery中访问Angular2变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆