Dependency Injection and AngularJS Routes
Categories: Angular Angular JS
Dependency Injection and AngularJS Routes
Dependency injection (DI) is a design pattern where dependencies are defined in an application as part of the configuration. Dependency injection helps you avoid having to manually create application dependencies. AngularJS uses dependency injection to load module dependencies when an application first starts. The app.js code in the previous section shows how AngularJS dependencies are defined.
As you can see, two dependencies are defined as needed by the helloWorldApp application at startup. The dependencies are defined in an array in the module definition. The first dependency is the AngularJS ngRoute module, which provides routing to the application.
The second dependency is our controller module, helloWorldControllers. We will cover controllers in depth later, but for now just understand that controllers are needed by our applications at startup time.
Dependency injection is not a new concept. It was introduced over 10 years ago and has been used consistently in various application frameworks; DI was at the core of the popular Spring framework written in Java. One of its main advantages is that it reduces the need for boilerplate code, writing of which would normally be a time-consuming process for a development team.
Dependency injection also helps to make an application more testable. That is one of the main advantages of using AngularJS to build JavaScript applications. AngularJS applications are much easier to test than applications written with most JavaScript frameworks. In fact, there is a test framework that has been specifically written to make testing AngularJS applications easy.
AngularJS Routes
AngularJS routes are defined through the $routeProvider API. Routes are dependent on the ngRoute module, and that’s why it is a requirement when the application starts. The following code from app.js shows how we define routes in an AngularJS application. Two
routes are defined — the first is / and the second is /show:
/* chapter1/app.js excerpt */
helloWorldApp.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider){
$routeProvider.
when('/', {
templateUrl: 'partials/main.html',
controller: 'MainCtrl' }).
when('/show', {
templateUrl: 'partials/show.html',
controller: 'ShowCtrl'
});
The two defined routes map directly to URLs defined in the application. If a user clicks on a link in the application specified as www.someDomainName/show, the /show route will be followed and the content associated with that URL will be displayed. If the user clicks on a link specified as www.someDomainName/, the / route will be followed and that content will be displayed.