如何将GitHub的gist嵌入到Angular模板中?

4

Angular在其模板中忽略script标签,但它们对于加载GitHub gist是必需的。最佳实践是什么?使用iframe吗?动态创建script标签?还是其他方式?

3个回答

5

一种方法是创建一个包含 scriptiframe,并在需要显示你的代码片段时附加它(基于 jasonhodges 的解决方案)。

模板

 <iframe #iframe type="text/javascript"></iframe> 

组件

@ViewChild('iframe') iframe: ElementRef;

gistUrl: string;

ngAfterViewInit() {
  const doc = this.iframe.nativeElement.contentDocument || this.iframe.nativeElement.contentElement.contentWindow;
    const content = `
        <html>
        <head>
          <base target="_parent">
        </head>
        <body>
        <script type="text/javascript" src="${this.gistUrl}"></script>
        </body>
      </html>
    `;
    doc.open();
    doc.write(content);
    doc.close();
}

1

使用angular-gistngx-gist嵌入GitHub代码片段。

angular-gist:

安装:

npm install angular-gist --save

作为模块的用法:

angular.module('myApp', ['gist']);

作为指令的用法:

<gist id="1234556"></gist>

ngx-gist:

安装:

npm i --save ngx-gist

使用方法:

import { NgxGistModule } from 'ngx-gist/dist/ngx-gist.module';

@NgModule({
    declarations: [
    AppComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        NgxGistModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

适用于您自己的实现:

查看如何使用iframe来实现此功能


"AngularJS指令用于嵌入Github Gists。我需要一个适用于Angular 2+的解决方案,最好没有冗余依赖项。" - iAmV
1
然后查看这些存储库的源代码。它们使用一个 iframe。 - user9973168

0

我已经多次使用angular-gist-embed,并使用Bower来实现它。

  • 只需像这样安装:bower install angular-gist-embed

  • 然后添加它:angular.module('myModule',['gist-embed'])

我使用特定的GitHub Gist id来嵌入它:

<code data-gist-id="5457595"></code>

您可以在这里找到更多示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接