Welcome!

APIs for the Internet of Things

Max Katz

Subscribe to Max Katz: eMailAlertsEmail Alerts
Get Max Katz via: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


Blog Feed Post

Understand 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

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.


Read the original blog entry...

More Stories By Max Katz

Max Katz heads Developer Relations for Appery.io, a cloud-based mobile app platform. He loves trying out new and cool REST APIs in mobile apps. Max is the author of two books “Practical RichFaces” (Apress 2008, 2011), DZone MVB (Most Valuable Blogger), and is a frequent speaker at developer conferences. You can find out what Max is up to on his blog: http://maxkatz.org and Twitter: @maxkatz.