cityCoder cityCoder - 3 months ago 40
AngularJS Question

AngularJS injector

Can anyone give a detail example of injector of AngularJS.
Here is the code copy from API.
"In the following example a new block of HTML containing a ng-controller directive is added to the end of the document body by JQuery. We then compile and link it into the current AngularJS scope."



<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<body ng-app="myApp">
</body>
<script>
angular.module('myApp', []);
var $div = $('<div ng-controller="formController">123</div>');
$('body').append($div);
angular.element(document.body).injector().invoke(function($compile) {
var scope = angular.element($div).scope();
$compile($div)(scope);
});

function formController ($scope,$http) {
}
</script>





I copy and paste it in a html page, but it does not work.with error "Uncaught ReferenceError: $ is not defined"

UPDATE:
I include jquery,and got a new error:
Uncaught TypeError: Cannot read property 'invoke' of undefined

Answer
  1. Create an angular module -- angular.module('myApp', []);
  2. Update the body element to use this module -- <body ng-app="myApp">
  3. Give some time for angular to bootstrap the application.

    setTimeout(function () {
        // now you can use the injector.
        var $div = $('<div ng-controller="formController">123</div>');
        $('body').append($div);
        angular.element(document.body).injector().invoke(function($compile) {
            var scope = angular.element($div).scope();
            $compile($div)(scope);
        });
    }, 100);
    

Your example should work with these changes.