ANGULARJS JQUERY

JQUERY – “Thinking in AngularJS” if I have a jQuery background

  • AngularJS is a good web app framework.
  • Become official documentation and samples, it looks superior among a large number of frameworks in an almost-real-world application test (the famous TodoMVC project).
  • But for a developer who has not used frameworks similar to Angular before, and has mostly worked with JavaScript libraries like jQuery, there may be some difficulty in shifting from the jQuery mindset to the Angular mindset.

Don’t design your page, and then change it with DOM manipulations

In jQuery, we are design a page, and then we make it dynamic, because jQuery was designed for augmentation and has grown incredibly from that simple premise.

But in AngularJS, we should start from the ground up with your architecture in mind. Instead of starting by thinking “we have this piece of the DOM and we want to make it do X”, we will start with what we want to accomplish, then go about designing your application, and then finally go about designing your view.

Don’t augment jQuery with AngularJS

We don’t start with the idea that jQuery does X, Y, and Z, so you will just add AngularJS on top of that for models and controllers.
This is really tempting when you’re just starting out, which is why you always recommend that new AngularJS developers don’t use jQuery at all, at least until they get used to doing things the “Angular Way”.
Many developers here and on the mailing list create these elaborate solutions with jQuery plugins of 150 or 200 lines of code that they then glue into AngularJS with a collection of callbacks and$applys that are confusing and convoluted.
The problem is that inmost cases that jQuery plugin could be rewritten in AngularJS in a fraction of the code, where suddenly everything becomes comprehensible and straightforward.
when solutioning, first “think in AngularJS”; if you can’t think of a solution, after all of that there is no easy solution, then feel free to reach for the jQuery.

Always think in terms of architecture 

We know single-page applications are applications. But not webpages.
So we need to think like a server-side developer in addition to thinking like a client-side developer.
We have to think about how to divide our application into individual, extensible, testable components.

So then how do you do that? How do you “think in AngularJS”? Here we are contrasted with jQuery.

The view is the “official record”

To change the view in JQuery. We could have a dropdown menu defined as a ul like so:

jQuery Code
<ul class="main-menu">
    <li class="active">
        <a href="#/home">Home</a>
    </li>
    <li>
        <a href="#/menu1">Menu 1</a>
        <ul>
            <li><a href="#/sm1">Submenu 1</a></li>
            <li><a href="#/sm2">Submenu 2</a></li>
            <li><a href="#/sm3">Submenu 3</a></li>
        </ul>
    </li>
    <li>
        <a href="#/home">Menu 2</a>
    </li>
</ul>

In your application logic activate in jQuery :

jQuery Code
$('.main-menu').dropdownMenu();

The view-based functionality in AngularJS. We would like to ul declaration:

jQuery Code
<ul class="main-menu" dropdown-menu>
    ...
</ul>

Recall:

Don’t design, and then mark up. You must architect, and then design.

Data binding

One of the best features of AngularJS and lot of the need to do the kinds of DOM manipulations.
AngularJS will automatically update your view so we don’t have to! In jQuery, we respond to events and then update content.

jQuery Code
$.ajax({
  url: '/myEndpoint.json',
  success: function ( data, status ) {
    $('ul#log').append('<li>Data Received!</li>');
  }
});

Data binding

For a view that looks like this:

jQuery Code
<ul class="messages" id="log">
</ul>

How do we test the logic apart from the DOM?

This a little disordered and a weak. But in AngularJS, we can do this:

jQuery Code
$http( '/myEndpoint.json' ).then( function ( response ) {
    $scope.log.push( { msg: 'Data Received!' } );
});

We are view can look like this:

jQuery Code
<ul class="messages">
    <li ng-repeat="entry in log">{{ entry.msg }}</li>
</ul>
jQuery Code
<div class="messages">
    <div class="alert" ng-repeat="entry in log">
        {{ entry.msg }}
    </div>
</div>

Now we are using an unordered list, and Bootstrap alert boxes.
Hence the log messages could also be editable in the view just by doing this: <input ng-model=”entry.msg” />.

Two-way Data Binding

Binding a DOM value to a model in a controller scope makes it truly linked to the scope variable.

jQuery Code
<input type="text" ng-model="yourName" placeholder="Enter a name here" />
<h1>Hello {{yourName}}!</h1>

Dependency Injection

Dependency injection is a technique whereby one object supplies the dependencies of another object.
A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it.

jQuery Code
DataSource = $resource(url, default_params, method_details)

DI means that we can declare components very freely and then from any other component, just ask for an instance of it and it will be granted.
we don’t have to know about loading order, or file locations, or anything like that.
The power may not immediately be visible, but we are providing one (common) example: testing.

In our application, we require a service that implements server-side storage through a RESTAPI and, depending on application state, local storage as well.
When running tests on our controllers, we don’t want to have to communicate with the server.
we’re testing the controller, We can just add a mock service of the same name as our original component, and the injector will ensure that our controller gets the fake one automatically.

Data Access

Model layer of an Angularjs (we can use plain data variables, objects, and arrays in any combination), it provides a convenient way to talk to a REST API on the server.
For example,

jQuery Code
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
  user.abc = true;
  user.$save();
});

Angular predefines reasonable defaults for getting, setting, deleting, and querying records.
And parametrized URLs give you the ability to customize data access to your needs.

Test-driven development

Test for the non-existent when-active directive

jQuery Code
it( 'should add "active" when the route changes', inject(function() {
    var elm = $compile( '<a href="/hello" when-active>Hello</a>' )( $scope );

    $location.path('/not-matching');
    expect( elm.hasClass('active') ).toBeFalsey();

    $location.path( '/hello' );
    expect( elm.hasClass('active') ).toBeTruthy();
}));

And when we run our test, we can confirm that it fails. Only now should we create our directive:

jQuery Code
.directive( 'whenActive', function ( $location ) {
    return {
        scope: true,
        link: function ( scope, element, attrs ) {
            scope.$on( '$routeChangeSuccess', function () {
                if ( $location.path() == element.attr( 'href' ) ) {
                    element.addClass( 'active' );
                }
                else {
                    element.removeClass( 'active' );
                }
            });
        }
    };
});

About the author

Wikitechy Editor

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

1 Comment

Click here to post a comment