0

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 have included jquery, and got a new error:

Uncaught TypeError: Cannot read property 'invoke' of undefined

7
  • You need to include jQuery. Commented Feb 25, 2015 at 8:10
  • Have you included jQuery in your project? Commented Feb 25, 2015 at 8:10
  • Thanks, I modified it, but got a new error msg. Commented Feb 25, 2015 at 8:14
  • include jquery before angularjs Commented Feb 25, 2015 at 8:18
  • @pixelbits, already changed it, but the error still exists Commented Feb 25, 2015 at 8:22

1 Answer 1

1
  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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have never use AngularJS before. I modified as you said, but it does not work, could you help me check whether my modification is wrong, or there still exist other error
Updated the answer. If it still doesn't work, please increase the timeout provided to the timeout function and try.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.