9

I'm trying to learn AngularJS and I'm trying to dynamically compile some DOM elements... I've tried the demo:

try {
        var templateHTML = angular.element('<p>{{total}}</p>'),
            scope = ....;

        var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
          //attach the clone to DOM document at the right place
        });

        //now we have reference to the cloned DOM via `clone`
} catch (ex) {
alert(ex.message);
}

but all I get back is a "$compile is not defined"

HELP!

user1122052
  • 341
  • 1
  • 3
  • 10
  • 1
    What does the rest of your controller look like, did you inject compile into the controller (e.g. controller('mycontroller', function($compile){...}). – Paul Ryan Jun 03 '13 at 23:09

2 Answers2

8

A sample code for using $compile in a directive. Basically go ahead & first append the element to DOM (might want to keep it invisible), then run the compile by using a finder.. as mentioned by rtcherry, $compile should be injected.

        //
        componentModule.directive('getCompilerWk', function($compile) {
          return {
            restrict: 'A',
            link: function(scope, elm, attr) {
              elm.click(function(){
                    $(body).append(templateHTML);
                    $compile($(body).find('p'))(scope);

              })
            }
          };
        });
6

Where are you calling this code from? Is it safe to assume it is outside of the Angular framework by your use of angular.element(...)?

If so, you can use this:

// Split across two lines for readability...
angular.element(<something within Angular's scope>)
    .injector().get('$compile')(...)

If not, you may simply need to inject $compile into the controller/directive/service.

rtcherry
  • 4,840
  • 22
  • 27