How to include angularjs javascript in wordpress post

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:

  1. We can just include the AngularJS javascript (angular.js) in post or page content itself.
  2. 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:

  1. Create a new plugin wp-angularjs-control-include with wp-angularjs-control-include.php file and js folder containing angular.js files. The plugin enqueues angular.js scripts based on custom variable wp-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.
  2. Install and activate the plugin.
  3. Set wp-angularjs-include to true for the desired wordpress post as shown below:
    wordpress-angularjs-include-custom-field

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:
wordpress-angularjs-include-example

Few points to note

  1. 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);
    });
  2. AngularJS may have some impact on SEO as some content is replaced dynamically on the page. Hence it seems more suitable dynamic apps.
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments