Embed Angular App Within Another Page?
Solution 1:
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
templateURL
s must be built dynamically. For example, ouput a script tag for URL to your plugin folder:<script>varMY_PLUGIN_BASE = '<?phpecho 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 ofbody
.
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 usingangular.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.
Post a Comment for "Embed Angular App Within Another Page?"