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!

1
  • 1
    What does the rest of your controller look like, did you inject compile into the controller (e.g. controller('mycontroller', function($compile){...}). Commented Jun 3, 2013 at 23:09

2 Answers 2

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);

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

Comments

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.

Comments

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.