Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed Angular App within another page?

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?

Edit: 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.

like image 818
Chainlink Avatar asked Jan 15 '14 19:01

Chainlink


1 Answers

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

  • 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>
    

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

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

    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.

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


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

  • 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'])
    
  • Use absolute URL for templateURL, and make sure that URL have CORS enabled.

  • Again, avoid using routes if possible. For the Wordpress plugin, we're pretty sure that there's no other app using hash for routing (Wordpress is using Backbone, but I don't see the routes), but in general there are already a MVC app on the page that handle routing.
like image 189
tungd Avatar answered Oct 14 '22 20:10

tungd