AngularJS Best Practices

Refactoring Existing Code to Angular

Start Small

Regardless of the type of code you’re refactoring, it’s usually best to start with a small component. It doesn’t always make sense to move everything into using some other library just because you can, but rather just change things as you need to develop new features or fix bugs. The simplest way to start is by taking a part of the code and replacing it with an Angular controller. Take away any code that modifies the DOM, and instead build it into the markup using Angular’s databinding features. You’ll definitely encounter cases where you need to access some more general code when doing this, which is a perfect case to move the code into a service. Then, it’s very easy to inject it into your controller.

Organizing Code

It’s usually a good idea to keep things simple. When you start, just create a page-specific angular module. This is probably quite obvious if you’re working with a single page app, but in a case where your app has traditional page changes, keeping modules on their own pages for starters is a good idea. As you keep adding things into the module, you’ll probably start seeing things that should be shared between controllers. In a case like that, you should move the code into a service.

Eventually you’ll start seeing cases where you need the same functionality in different modules. When this happens, create a base module and put the shared things there. You can then add a dependency to the base module into your page-specific modules.

Dealing with the DOM

You can easily move much of legacy DOM handling code into Angular simply by using Angular’s builtin directives and databinding features. However, in the likely case that you have used some jQuery plugins or done some other slightly more involved DOM trickery, things may be a tiny bit more difficult to sort out.

The most straightforward things can easily be wrapped into a directive. Sometimes the only thing you need to do is take the jQuery (or other) function call, wrap it in a directive and call it a day. For anything nontrivial, it’s usually worth checking out whether you can simply plug in Angular UI and be done with it. Even if that’s not the case, you can use their code as an example on how to do more complex plugin integrations or such into directives.

Working with Legacy Code
Especially with large applications, it’s often not feasible to move everything into Angular at once. You’re going to need to access your Angular services from some of the legacy code, and you’re also going to need to be able to respond to changes that happen via legacy event handlers inside your Angular code.

Copyright © All Rights Reserved - C# Learners