Integrating AngularJS with Existing JavaScript and jQuery

The fact that AngularJS is based on JavaScript and jQuery makes it tempting to simply try to add it to existing applications to provide data binding or other functionality. That approach will almost always end up in problem code that is difficult to maintain. However, using AngularJS doesn’t mean that you need to simply toss out your existing code either. Often you can selectively take working JavaScript/jQuery components and convert them to either directives or services.

This also brings up another issue: when to use the full version of jQuery as opposed to the jQuery lite version that is provided with AngularJS? I know that many people have strong views in both directions. On one hand, you want to keep your implementation as clean and simple as possible. But on the other hand, there might be times when you need functionality that’s available only in the full version of jQuery. My take, as always, is to use what makes sense. If I need functionality that is not provided with AngularJS jQuery lite, I will load the full library. I’ll discuss the mechanics of loading jQuery as opposed to jQuery lite later in this chapter.

The following steps suggest a method to integrate AngularJS into your existing JavaScript and jQuery applications:

1. Write at least one small AngularJS application from the ground up that uses a model, custom HTML directives, services, and controllers. In other words, in this application, ensure that you have a practical comprehension of the AngularJS separation of responsibilities.

2. Identify the model portion of your code. Specifically, try to separate out the code that augments the model data in the model into controller functions and code that accesses the back-end model data into services.

3. Identify the code that manipulates DOM elements in the view. Try to separate out the DOM manipulation code into well-defined custom directive components and provide an HTML directive for them. Also identify any of the directives for which AngularJS already provides built-in support.

4. Identify other task-based functions and separate them out into services.

5. Isolate the directives and controllers into modules to organize your code.

6. Use dependency injection to link up your services and modules appropriately.

7. Update the HTML templates to use the new directives.

Obviously, in some instances it just doesn’t make sense to use much if any of your existing code. However, by running through the preceding steps, you will get well into the design phase of implementing a project using AngularJS and can then make an informed decision.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset