Understanding AngularJS Dependency Injection in Appery.io App

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 those object that you need without doing any work.

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

angular.module('myApp', [])
.controller('MyController', function($scope, $q, $timeout) {
  // $scope, $q, and $timeout objects 
  // are injected and available in here

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
Ionic page

The is the controller editor after opening the Scope view:

Screen Shot 2015-10-15 at 3.43.40 PM
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 Apperyio.get() function to do dependency injection. This function is just a wrapper to AngularJS $inject.get() function. It is this function that knows how to get an instance of the service you need reference to.

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

var $scope = Apperyio.get("$scope");
var $q = Apperyio.get("$q");
var $timeout = Apperyio.get("$timeout");

This approach still use the same AngularJS Dependency Injection, it is just a different way to do exactly the same task. Using this approach you can inject a dependency only when you actually needed in the code. You don’t have to list them all at the top. Also, 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 Appery.io account and start building today.

Published by

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.