AngularJS – Dependency Injection


http://docs.angularjs.org/guide/di

Some more learning about AngularJS. Dependency injection is a major feature of Angular, and it’s where magics are happening. I still haven’t been able to get the clear understanding, but the above video helped some.

Angular’s dependency injection features allow to connect the controller with services through the argument-name listed in the constructor. Just aligning the argument-names with the defined service names makes Angular’s injector find the corresponding services. Services can be defined through Module.service, Module.factory, Module.value functions. Also, you can inject dependency for certain pre-defined services, like exception handler ($exceptionHandler). By hooking up with them, you can change the behavior as you like.

The followings are some trials I made.

http://jsfiddle.net/tbDCZ/

<html ng-app="app">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular-resource.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

    <script>
      var app = angular.module('app', ['ngResource']);

      /* --------- Service Definitions --------*/
      // Using module.value
      app.value('sampleValue', 'Returned Sample Value');

      // Using module.factory
      app.factory('sampleFactory', function() {
        return {
          func : function() {
           return "Returned Sample Factory";
          }
        }
      });

      // Using module.service
      app.service('sampleService', function() {
        this.func = function() {
          return "Returned Sample Service";
        }
      });

      // Adding arguments (sampleXXX) allows to refer defined services, through argument names.
      app.directive('sample', function($parse, sampleValue, sampleFactory, sampleService) {
        return {
          link: function(scope, element, attr) {
            element.text('[sampleValue] is "' + sampleValue + '", ' +
                         '[sampleFactory] is "' + sampleFactory.func() + '", and ' +
                         '[sampleService] is "' + sampleService.func() + '".');
          }
        }
      });

      /* --------- Exception Handler ---------*/
      // using module.factory
      app.factory('$exceptionHandler', function($window) {
        return function(e) {
          //$window.alert(e);
          $("#error").text(e);  // using jQuery. Not sure how to access $scope.
        }
      });

      // using module.value
      /*app.value('$exceptionHandler', function(e) {
        alert(e);
      });*/

      function SampleCtrl($scope) {
        $scope.showError = function() {
          throw new Error('Sample Error Message');
        };
      }
    </script>

    <style type="text/css">
      .error {
        background-color: #fcc;
      }
    </style>
  </head>
  <body ng-controller='SampleCtrl'>
    <div>
      <div sample></div>
      <br/>
      <div ng-click="showError()">Click this message to throw an error.</div>
      <br/>
      <div id="error" class="error">Error message comes here.</div>
    </div>
  </body>
</html>
Advertisements

Posted on March 4, 2013, in JavaScript. Bookmark the permalink. Leave a comment.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: