1

What I want to do is to append compiled template to some other DOM element in Angualrjs directive. Is it possible? How?

I know you can use transclude to include the template and keep content in the tag, but how do I attach my compiled template to other DOM element?

angular.module("my.directive")
.directive('passwordStrength', [function(){
    return {
        templateUrl: '/tpl/directive/passwordStrength.html',
        restrict: 'A',
        link: function postLink(scope, iElement, iAttrs){
            console.log('password strength is running');
            iElement.append($template) // problem here!!!


        }
    };
}]);
1
  • Try to compile template code before appending. Commented Nov 18, 2014 at 4:57

1 Answer 1

1

I'm not sure what you're trying to accomplish overall. You may want to use ng-include to pull in markup from a url, rather than using the templateUrl property, or you may want to use the templateUrl property on one directive, then make another directive and include that directive in the second directive. I made some sample directives to help give you ideas.

.directive('myDirective', function($compile) {
  return {
     scope: {
       path: '=myDirective'
     },
     link: function(scope, element) {
      // rather than use `templateUrl`, I'll get markup from the path using `ng-include`
      var html = '<div ng-include="path"></div>';
      // manipulate the markup however you want to
      html+= '<p>More stuff from "myDirective"!</p>';
      // append the markup
      element.append(html);
      // compile the markup so that Angular will know about it (or use the directive `compile` rather than `link`)
      $compile(element.contents())(scope);
    }
  };
})

// this is sort of like "extending" the other directive.
.directive('myOtherDirective', function() {
  return {
    scope: {
      path: '=myOtherDirective'
    },
    template: '<p>Stuff from "myOtherDirective"></div><div my-directive="path"></div>'
  };
})

Here's a demo you can mess around with.

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

1 Comment

Thanks, I need to compile the tempalte.

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.