Understanding AngularJS Dependency Injection in Appery.io Apps

Dependency Injection (DI) in AngularJS is one of the core capabilities of the framework. You simply specify on which objects a particular controller depends, and AngularJS will automatically (and somewhat magically) inject those objects into your controller without you needing to do anything. In other words, you are going to get a reference to the objects that you need without doing any work.

The following is an example of a controller with three objects injected:

The Appery.io platform simplifies building AngularJS apps. For example, when you create a new Ionic (or Bootstrap) page, the Appery.io App Builder will automatically create a controller for that page. You can see the controller by switching to Scope view:

screen-shot-2015-10-15-at-3-38-55-pm (1)

Ionic page

The is the controller editor after opening the Scope view:

screen-shot-2015-10-15-at-3-43-40-pm (2)

Scope editor


You can quickly create a scope function by entering its name and clicking the Add button on the right side. How do you inject objects into a function? You still use the same AngularJS injection, but you set it up in a slightly different way. Instead of listing the dependencies as above, you call the Apperyio.get() function to do dependency injection. This function is just a wrapper to the AngularJS $inject.get() function. It is this function that knows how to get an instance of the service you need a reference to.

For example, to inject the same three objects from the above code snippet, you would simply write this code:

This approach still uses the same AngularJS Dependency Injection. It’s just a different way to do exactly the same task. Using this approach you can inject a dependency only when you actually need it in the code. You don’t have to list them all at the top. Also, the Apperyio.get() function might have additional features, so it’s a good idea to use it.

Want to build apps faster? Then, sign up for an Appery.io account and start building today.