【问题标题】:Angular 6 - Setting a method as the `data-*` attribute for an elementAngular 6 - 将方法设置为元素的`data-*`属性
【发布时间】:2019-07-21 03:43:16
【问题描述】:

我的component.ts 看起来像这样:

import { Component, OnInit, AfterViewInit, ElementRef, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
import { environment } from '../../../environments/environment';


@Component({
  selector: 'app-requester',
  template: '<div id="btn-dlg-container"></div></div>',
})
export class RequesterComponent implements OnInit, AfterViewInit {
  private externalJSHost = 'URI pointing to external JS';

  constructor(
    @Inject(DOCUMENT) private document, private elementRef: ElementRef
  ) { }

  ngOnInit() {
  }

  ngAfterViewInit () {
    const s2 = document.createElement('script');
    s2.type = 'text/javascript';
    s2.src = this.externalJSHost; // external script
    s2.id = 'dlshare';
    s2.setAttribute('data-callback', this.callBackMethod); // This is where the problem is
    document.body.appendChild(s2);
 }

  callBackMethod() {
    console.log('SUCCESS !!!');
  }

}

我创建的script 元素需要一个data-callback 属性,它应该是一个函数。该函数在脚本执行后执行。

显然,Element.setAttribute(documentation) 只接受一个 String 作为第二个参数。

如何重写此代码,以便将callBackMethod 设置为我动态创建的script 元素的data-callback 属性?

【问题讨论】:

    标签: javascript angular html angular6


    【解决方案1】:

    为什么不在脚本加载后直接调用方法

    其实你可以通过window对象定义一个全局函数,并传递函数的名称(字符串)。

    ngAfterViewInit () {
      window.my_global_callback = (data) => {
          console.log(data);
          this.callBackMethod();
      };
      const s2 = document.createElement('script');
      s2.type = 'text/javascript';
      s2.src = this.externalJSHost; // external script
      s2.id = 'dlshare';
      s2.setAttribute('data-callback', 'my_global_callback'); 
      document.body.appendChild(s2);
     }
    

    此外,如果您想让全局回调的名称动态化(如果您有多个组件实例并且希望每个实例都有自己的回调,您可能希望这样做),您可以生成一个唯一的 ID(How to generate UUID in angular 6 ) 将其保存在变量中并执行:

    ...
    window[uniqueGlobalCallbackVarName] = (data) => {
          console.log(data);
          this.callBackMethod();
    };
    ...
    s2.setAttribute('data-callback', uniqueGlobalCallbackVarName);
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 2018-12-17
      相关资源
      最近更新 更多