Showing results for 
Search instead for 
Did you mean: 

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 thinkabout development, a little.)

Getting its hang isn't that simple, however. In the wake of experiencing a fundamental instructional exercise I had an inclination that I knew what I could do, yet didn't discover straightforward code tests for some basic necessities. So I battled, a bit, and something I battled with is the means by which to do DOM control in AngularJS.

jQuery is effectively incorporated into AngularJS, so effortlessly that the best DOM control instructional exercise I discovered utilized jQuery, despite the fact that it says on the case that you can do most controls with AngularJS, without likewise stacking jQuery.

So — here's an agonizingly basic depiction of the linguistic structure used to do AngularJS DOM control. Possibly it will spare somebody some sweat.

We more often than exclude something like this in any powerful 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=""></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).

Tags (2)
Version history
Revision #:
1 of 1
Last update:
‎02-14-2018 09:59 PM
Updated by: