top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is $injector and $inject?

0 votes
208 views
What is $injector and $inject?
posted Nov 18, 2017 by Jayshree

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

$injector is a service which is used to invoke controller functions, service functions, filter functions, and
any other function that might need dependencies as parameters. Angular creates only a single $injector object
when an application is bootstrapped and uses that object for invoking.

<script>
 var app = angular.module('app', []);
 app.service('s1', function () {
 this.value = 22;
 });
 app.controller("MyCtrl", function ($scope, $injector) {
 $scope.doSomething = function () {
 var s1 = $injector.get('s1')
 s1.value += 10
 }
 $scope.value = function () {
 var s1 = $injector.get('s1')
 return s1.value
 }
 });
 </script>
 <div ng-app="app" ng-controller="MyCtrl">
 <button ng-click="doSomething()">increment</button>
 {{value()}}
 </div>

$inject is property which is used to inject the dependencies of a function as an array of strings.

<script type="text/javascript">
 var MyController = function(renamed$scope, renamedGreeter) {
 // ...
 }
 MyController['$inject'] = ['$scope', 'greeter']; //inject dependencies as an array of
strings
</script>
answer Nov 18, 2017 by Shivaranjini
...