【问题标题】:How to use Angular 4 variable inside Jquery Function如何在 Jquery 函数中使用 Angular 4 变量
【发布时间】:2018-04-12 23:14:21
【问题描述】:

这个问题已经得到了一些回复here。但这似乎对我不起作用。

我正在尝试使用 jQuery 创建树结构。问题是我不能在 jQuery 函数中使用声明的 angular 4 变量。这是代码。

employees = ["Mr. John", "Mr. Steve"];

ngOnInit() {
   (function($) => {
      function OrgChart($container, opts){
          console.log(this.employees);
      }
   });
}

我在控制台中看到一条错误消息,“在针对 ES3 或 ES5 时,严格模式下的块内不允许函数声明”

【问题讨论】:

  • 如果您可以逐步描述您认为这段代码应该做什么,这可能会有所帮助。下面是它现在所做的:1) 在 Angular 组件初始化时,2) 声明一个接受单个参数 $, 的匿名函数 3) 在这个匿名函数中,声明一个命名函数 OrgChart,它接受两个参数 $container并选择。 4) 在 OrgChart 函数中,使用单个参数调用控制台方法 log,该参数是组件的属性 employees。在任何时候都不会调用匿名函数或命名函数 OrgChart。

标签: javascript jquery angular


【解决方案1】:

第一个(employees of undefined 问题)

要绑定组件的“this”,请为函数使用箭头符号:

($) => { console.log(this.employees)}

而不是function($) { ... }

第二个(“块内不允许函数声明”)

你可以在你的 Angular 组件的另一个地方声明你的其他内部函数,然后引用它:

ngOnInit() {
    // this declaration is nonsense to me, this will declare a function that is never called and exists only here, but anyway... 
    ($) => {
        // you can call OrgChart here : 
        this.OrgChart()
    } 
}

OrgChart($container, opts) { 
    console.log(this.employees); 
}

【讨论】:

  • 感谢您的努力,但这似乎并没有解决目的。我已经修改了这个问题,因为即使我遵循了这个问题,我仍然会收到错误。
  • 我刚刚看到你的编辑,所以现在它变成了另一个问题。我仍然不太了解您要做什么,但请注意:使用箭头符号,您不能编写关键字“函数”。另外,你到底想达到什么目的?
  • 我一定对 jQuery 生疏了,但是我越看这段代码,我就越觉得它根本没有做任何事情。
  • 这是存在问题的代码的修改部分。 OrgChart 函数中存在许多其他 jQuery 东西,它使用 jQuery 为我构建了一个层次结构的树结构。只是我需要使用在此函数外部声明的员工数组来构建树,而不是使用在函数内部声明的一些虚拟数据。
  • 好的,不知道如何回答,因为我自己无法真正测试,但我试图为第二个问题提供一些额外的线索。
【解决方案2】:

在启动 jquery 块之前,您需要将角度组件引用存储在另一个变量中。

export class PlanGruposComponent implements OnInit {
   group = 'Meu grupo';

   OnInit() {

       //reference of currect component object
       let temporaryThis = this; 

       $(document).ready(function () {
          console.log("Print : " + temporaryThis.group);
       });

   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多