Hey. Help deal with this feature.

function simpleService(){ this.name = "simpleService"; } angular.module('foo', []) .service('simpleService', simpleService); var myInjector = angular.injector(['foo']); var service = myInjector.get('simpleService'); alert(service.name); 

As far as I understood this thing gets services from the side of the module.

But in one of the projects I met the following:

 controller('MyCtrl2', ['$scope', '$injector', function($scope, $injector) { require(['controllers/myctrl2'], function(myctrl2) { // injector method takes an array of modules as the first argument $injector.invoke(myctrl2, this, {'$scope': $scope}); } }) 

myctrl2.js

 define([], function() { return ['$scope', '$http', function($scope, $http) { // You can access the scope of the controller from here $scope.welcomeMessage = 'hey this is myctrl2.js!'; // because this has happened asynchroneusly we've missed // Angular's initial call to $apply after the controller has been loaded // hence we need to explicityly call it at the end of our Controller constructor $scope.$apply(); }]; }); 

What are these tricks?

    1 answer 1

     var myInjector = angular.injector(['foo']); var service = myInjector.get('simpleService'); 

    This is a non-standard way to get a provider. Using $injector.get you can get different types of providers as provider, service, constant, value, factory, decorator , as follows:

     angular.injector(arrayOfModulesToLoad).get(providerName) 

    In one application, this syntax is hardly useful to you, since angular itself deals with Dependency Injection when we write:

     angular.module('foo').controller('myController', function (simpleService) { // ... } 

    However, $injector.get useful especially if we want to get a provider outside the application, for example, from the browser console js:

     angular.element('body').injector().get('simpleService')