AngularJS Meet Open Atrium
The recent 2.23 version of Open Atrium contains a cool new interactive site builder and navigator application (see it in action). This application was written using the AngularJS framework. The combination of Drupal, jQuery, and AngularJS proved to be powerful, but wasn’t without some pitfalls.
Using AngularJS in Drupal
The basics of using Angular within Drupal is pretty straight-forward. Simply reference the external AngularJS scripts using the drupal_add_js() function, then add your custom javascript app code, then use a tpl template to generate the markup including the normal Angular tags. For example, here is the Drupal module code, javascript and template for a simple Angular app:
// Implements hook_menu()
function myapp_menu() {
$items['myapp'] = array(
'page callback' => 'myapp_menu_callback',
'access callback' => TRUE,
);
return $items;
}
// The menu callback to display the page
function myapp_menu_callback() {
drupal_add_js('https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js');
$base = drupal_get_path('module', 'myapp');
// data you want to pass to the app
drupal_add_js(array(
'myapp' => array(
'title' => t('Hello World'),
),
), 'setting');
drupal_add_js($base . '/myapp.js');
drupal_add_css($base . '/myapp.css');
return theme('myapp', array());
}
// Implements hook_theme().
function myapp_theme() {
return array(
'myapp' => array(
'template' => 'myapp',
),
);
}
(function ($) {
var app = angular.module("myApp", []);
app.controller("myAppController", function($scope) {
$scope.settings = Drupal.settings.myapp;
$scope.count = 1;
$scope.updateCount = function(value) {
$scope.count = $scope.count + value;
}
$scope.myClass = function() {
return "myclass-" + $scope.count;
}
})
}(jQuery));
<div class="myapp" ng-app="myApp" ng-controller="myAppController">
<h3 ng-class="myClass()">{{settings.title}}</h3>
<p>
<a class="btn btn-default" ng-click="updateCount(1)">Click</a>
to increment {{count}}
</p>
</div>
Now, obviously we aren’t using the full Angular framework here. We aren’t using any directives, nor are we really using Angular as a MVC framework. But it gives you the idea of how easy it is to get started playing with basic Angular functionality.
Angular plus jQuery
Developing javascript applications in Angular requires a different mindset from normal Drupal and jQuery development. In jQuery you are often manipulating the DOM directly, whereas Angular is a full framework that allows data to be bound and manipulated on page elements. Trying to combine both is often a source of frustration unless you understand more about how Angular works behind the scenes. Specifically, Angular has it’s own execution loop causing a mix of Angular and jQuery code to not seem to execute in a straightforward order. For example, in the above code, we set the class of the H3 based on the current “count” variable. What if we modified the updateCount function to try and set a css property for this class:
$scope.updateCount = function(value) {
$scope.count = $scope.count + value;
$('.' + $scope.myClass()).css('color', 'red');
}
If you click the button you’ll notice that the css color does NOT change to red! The problem is that Angular is executing the query function call BEFORE it actually updates the page. You need to delay the jQuery so it executes after the current Angular event loop is finished. If you change the code to:
$scope.updateCount = function(value) {
$scope.count = $scope.count + value;
setTimeout( function() {
$('.' + $scope.myClass()).css('color', 'red');
}, 1);
}
then it will work. The timeout value can be anything greater than zero. It just needs to be something to take the jQuery execution outside the Angular loop. Now, that was a horrid example! You would never actually manipulate the css and class properties like this in a real application. But it was a simple way to demonstrate some of the possible pitfalls waiting to trap you when mixing jQuery with Angular.
Drupal Behaviors
When doing javascript the “Drupal way”, you typically create a behavior “attach” handler. Drupal executes all of the behaviors when the page is updated, passing the context of what part of the page has changed. For example, in an Ajax update, the DOM that was updated by Ajax is passed as the context to all attached behavior functions. Angular doesn’t know anything about these behaviors. When Angular updates something on the page, the behaviors are never called. If you need something updated from a Drupal behavior, you need to call Drupal.attachBehaviors() directly.
Angular with CTools modals
In the Open Atrium site map, we have buttons for adding a New Space or New Section. These are links to the Open Atrium Wizard module which wraps the normal Drupal node/add form into a CTools modal popup and groups the fields into “steps” that can be shown within vertical tabs. This is used to provide a simpler content creation wizard for new users who don’t need to see the full node/all form, and yet still allows all modules that hook into this form via form_alters to work as expected. The tricky part of this is that as you navigate through the sitemap, Angular is updating the URLs of these “New” links. But CTools creates a Drupal Ajax object for each link with the “ctools-use-modal” class in it’s Drupal behavior javascript. This causes the URL of the first link to be cached. When Angular updates the page and changes the link URLs, this Ajax object cache is not updated. To solve this within the Open Atrium Sitemap app, an event is called when the page is updated, and we update the cached Ajax object directly via the Drupal.ajax array. This was a rather kludgy way to handle it. Ultimately it would be better to create a true Angular “Directive” that encapsulates the CTools modal requirements in a way that is more reusable.
Summary
Angular can be a very useful framework for building highly interactive front-ends. Using Drupal as the backend is relatively straight-forward. Angular allowed us to create a very cool and intuitive interface for navigating and creating content quickly within Open Atrium far easier than it would have been in jQuery alone. In fact, we began the interactive site map tool in jQuery and the code quickly became unmanageable. Adding functionality such as drag/drop for rearranging your spaces and sections would have been a mess in jQuery. In Angular it was very straight-forward. Once you understand how Angular works, you’ll be able to blend the best of Drupal + jQuery + Angular into very rich interfaces. Programming in Angular is very different. Learn more about Angular on the Phase2 blog!