Angular在其模板中忽略script
标签,但它们对于加载GitHub gist是必需的。最佳实践是什么?使用iframe
吗?动态创建script
标签?还是其他方式?
Angular在其模板中忽略script
标签,但它们对于加载GitHub gist是必需的。最佳实践是什么?使用iframe
吗?动态创建script
标签?还是其他方式?
一种方法是创建一个包含 script
的 iframe
,并在需要显示你的代码片段时附加它(基于 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();
}
使用angular-gist或ngx-gist嵌入GitHub代码片段。
安装:
npm install angular-gist --save
作为模块的用法:
angular.module('myApp', ['gist']);
作为指令的用法:
<gist id="1234556"></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 { }
我已经多次使用angular-gist-embed,并使用Bower来实现它。
只需像这样安装:bower install angular-gist-embed
然后添加它:angular.module('myModule',['gist-embed'])
我使用特定的GitHub Gist id来嵌入它:
<code data-gist-id="5457595"></code>
您可以在这里找到更多示例。