AngularJS: angular.injector with example

From AngularJS documentation

angular.injector : angular.injector(modules, [strictDi]);
                              return Injector object $injector

Creates an injector object that can be used for retrieving services as well as for dependency injection

Sometimes you want to get access to the injector of a currently running Angular app from outside Angular. Perhaps, you want to inject and compile some markup after the application has been bootstrapped. You can do this using the extra injector() added to JQuery/jqLite elements.

Example

Lets take a scenario where you have to generate buttons based on ajax response. The html which will be generated will have controller and action attached to button.

<!doctype html>
<html>
<head>
<script src="jquery.js"></script>
<script src="angular.min.js"></script>
<html>
<body ng-app="demoApp">
 <div ng-controller="DemoController"></div>
</body>
</html>
var app = angular.module('demoApp', []);
  app.controller('DemoController', function($scope, $http) {
   $http({
     method: 'GET',
     url: '/testInjector'
   }).then(function successCallback(response) {
    if(response.data.showButton == true){
     var injectHtml = $("<div ng-controller="InjectedController">
<input ng-click="click()" type="button" value="{{testValue}}" /></div>
");
     $("body").append(injectHtml);
     angular.element(injectHtml).injector().invoke(function($compile) {
       var scope = angular.element(injectHtml).scope();
       $compile(injectHtml)(scope);
     });
    }
   }, function errorCallback(response) {
    
   });
  });
  
  app.controller('InjectedController', function($scope) {
   $scope.testValue = "Injected Button";
   $scope.click = function(){ 
    alert("I am clicked");
   };
  });













Please follow the link for more reference about injector methods.

Good Day :)

Post a Comment

0 Comments