AngularJS is great framework for declaring dynamic views in HTML documents. To include AngularJS we just need to include the angularjs javascript file in the wordpress. These are two possible ways to include AngularJS in wordpress post:
- We can just include the AngularJS javascript (angular.js) in post or page content itself.
- angular.js can be included in page header or footer using a plugin. We can use a custom variable to decide if a specific post needs to have it or not.
Using first approach is pretty trivial. The second approach is little more cleaner. I’ll cover 2nd approach in this article.
WordPress plugin to include AngularJS
Here are the steps to create and activate the plugin to include AngularJS in wordpress:
- Create a new plugin
wp-angularjs-control-include
withwp-angularjs-control-include.php
file andjs
folder containing angular.js files. The plugin enqueues angular.js scripts based on custom variablewp-angularjs-include
(or any other variable you prefer). Here is how the code looks like for this:
<?php function waci_enqueue_js () { global $post; $post_angularjs_include_value = get_post_meta($post->ID, 'wp-angularjs-include', true); if (in_array($post_angularjs_include_value, array('true', '1')) ) { wp_enqueue_script('angularjs-js', plugins_url('js/angular.js', __FILE__), null, null, true/*in_footer*/); } } add_action('wp_enqueue_scripts', 'waci_enqueue_js'); ?>
Note that this will include angular.js in the html page footer. Including js in footer is a recommended practice from rendering perspective. - Install and activate the plugin.
- Set wp-angularjs-include to true for the desired wordpress post as shown below:
Sample AngularJS app
To create a sample wordpress app include the following code in your post:
<div ng-app> <label>Name:</label> <input type="text" ng-model="yourName" ng-init="yourName='Foo'"> <hr> <b>Hello {{yourName}}!</b> <div/>Note the
ng-app
in div tag and ng-model="yourName"
in input tag. This should be outcome of the above code:Few points to note
- AngularJS can be placed anywhere in the document. It only applies to relevant part of the HTML document once the document is ready as per the following code in angular.js:
jqLite(document).ready(function() { angularInit(document, bootstrap); });
- AngularJS may have some impact on SEO as some content is replaced dynamically on the page. Hence it seems more suitable dynamic apps.