在另一个页面中嵌入 Angular 应用程序? [英] Embed Angular App within another page?

查看:31
本文介绍了在另一个页面中嵌入 Angular 应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 javascript 应用程序,该应用程序在我无法控制的另一个页面中调用.我希望能够嵌入 Angular JS 应用程序,但如何在不修改 URL 的情况下处理路由?在这种情况下,测试(即 e2e)将如何工作?

I'm writing a javascript app which is called within another page I do not control. I'd like to be able to embed an Angular JS app, but how do I handle routing without modifying the URL? How would testing (ie. e2e) work in this scenario?

该应用程序是一个覆盖在 Wordpress 仪表板上的 wordpress 插件,因此无法修改 URL 和页面历史记录.该应用程序将绑定到嵌入在页面中的 div,并使用 CSS 覆盖在现有内容上.

The app is a wordpress plugin which is overlayed on the Wordpress dashboard, therefore the URL and Page History cannot be modified. The app will be bound to a div which is embedded in the page, and overlayed on existing content using CSS.

推荐答案

我相信你可以查询 AngularJS 和你的应用程序,并使用钩子来提供必要的 HTML.不过有几点需要注意:

I believe you can just inquire AngularJS and your app, and using hooks to provide necessary HTML. A few things to note though:

  • 由于 URL 无法更改,您应该在旧模式(使用 URL 哈希)而不是 HTML5 模式下使用路由器.
  • 由于您在生成的 URL 中运行,因此必须动态构建 templateURL.例如,将 URL 的脚本标记输出到您的插件文件夹:

  • Because the URL cannot be changed, you should use router in legacy mode (using URL hash) instead of HTML5 mode.
  • Since you're running in generated URL, the templateURLs must be built dynamically. For example, ouput a script tag for URL to your plugin folder:

<script>var MY_PLUGIN_BASE = '<?php echo plugins_url(); ?>'</script>

然后使用该常量定义您的路由和 templateURL:

And then later define your route and templateURL using that constant:

$routeProvider
  .when('/', {
    templateUrl: MY_PLUGIN_BASE+'my-plugin/views/main.html',
    controller: 'Main'
  })

这行得通,但通常我会避免在这种情况下使用路由.这会导致控制器和指令中的更多工作,但它更安全,因为页面上可能有其他客户端 MVC 应用.

This works, but in general I will avoid using routes in such situations. This cause more work in the controllers and directives, but it is safer because there could be other client side MVC apps on the page.

ng-app 附加到视图的根元素,而不是 body.

The ng-app is attached to the root element of your view instead of body.

对于更通用的嵌入式 AngularJS 应用程序(以我的经验:书签),您需要:

For more general embedded AngularJS app (in my experience: a bookmarklet), you need to:

  • 如果需要,注入 AngularJS(检查 window.angular)、CSS 和 HTML.
  • 注入应用的 JS 文件.因为只有一个 ng-app 会被自动引导,所以使用 angular.bootstrap

  • Inject AngularJS if needed (check for window.angular), CSS and HTML.
  • Inject your app's JS file. Because only one ng-app will be auto bootstraped, bootstrap your app manually using angular.bootstrap

angular.bootstrap(document.getElementById('my-app'), ['MyApp'])

  • templateURL 使用绝对 URL,并确保该 URL 已启用 CORS.

  • Use absolute URL for templateURL, and make sure that URL have CORS enabled.

    这篇关于在另一个页面中嵌入 Angular 应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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