DOM Manipulation in AngularJS — Without jQuery

jQuery is a great scripting library and I use it all the time, but for Single Page Applications the fairly new AngularJS framework can do a lot more, once you get the hang of it (and change the way you think about development, a little.)

Getting the hang of it isn’t that easy, though. After going through a basic tutorial I felt like I had a sense of what I could do, but didn’t find simple code samples for some common requirements. So I struggled, a little, and one of the things I struggled with is how to do DOM manipulation in AngularJS.

jQuery is easily integrated into AngularJS, so easily that the best DOM manipulation tutorial I found used jQuery, even though it says on the box that you can do most manipulations with AngularJS, without also loading jQuery.

So — here’s a painfully simple description of the syntax used to do AngularJS DOM manipulation. Maybe it will save someone some sweat.

We usually include something like this in any dynamic Web page:

<html>
  <body>
    <div class="noscript">
      <p>Javascript must be enabled for this to work.</p>
    </div>

    <div id="app" class="hide">
      <!-- Application mark-up goes here. -->
    </div>
  </body>
</html>

And a jQuery script:

$(function() {
  $(".noscript").addClass("hide");
  $("#app").removeClass("hide");
});

Now, if the user agent lacks JavaScript, we tell them they need it and hide the application. This is very easy with jQuery, but also very easy with pure AngularJS, once you get it.

In the head of the HTML page, which you’ll come to think of as the “View”, you load AngularJS and your application:

...
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
  <script src="js/myApp.js"></script>
</head>
...

myApp.js will define a module which will contain only a directive. A directive is the AngularJS feature where DOM manipulations go. The module will look like this:

var myModule = angular.module( 'myModule', [] );

myModule.directive( 'myDirective', function() {
  var linkFn;
  linkFn = function( scope, element, attrs ) {

    // The next two lines duplicate the effect of the jQuery above.
    angular.element( '#page' ).removeClass( 'hide' );
    angular.element( '.noscript' ).addClass( 'hide' );
  }

  return {
    restrict: 'C',
    link: linkFn
  }
})

When the AngularJS documentation says that angular.element( element )

Wraps a raw DOM element or HTML string as a jQuery element. angular.element can be either an alias for jQuery function, if jQuery is available, or a function that wraps the element or string in Angular’s jQuery lite implementation (commonly referred to as jqLite).

— this is what they mean.