-1

I have a directive that might look like this:

a.directive('autoResize', function($compile) {
  return {
    scope: {},
    link: function(scope, elem) {
      // HTML here is just an example
      var template = angular.element('<div some-angular-stuff></div>');
      $(elem).append(template);
      template = $compile(template)(scope);
    }
  }
});

When I compile to isolate scope it's not working. No content is shown. Seems like it would work if I compile to the parent scope. Any chance I could use the isolate scope?

Thanks

2
  • Your link is 404. Commented Jun 5, 2019 at 13:25
  • 1
    jsfiddle.net/sh0ber/6m54x9hc Your code works no problem for me Commented Jun 5, 2019 at 13:31

2 Answers 2

0

$compile returns a function that when you call it returns an element so you need to append it to the DOM by yourself:

angular.module('app', [])
  .controller('ctrl', function() {})
  .directive('autoResize', function($compile) {
    return {
      scope: {},
      link: function(scope, elem) {
        // HTML here is just an example
        var template = $compile(angular.element('<div some-angular-stuff></div>'))(scope);
        $(elem).append(template);
        console.log($(elem).html());
      }
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
  <auto-resize></auto-resize>
</div>

https://docs.angularjs.org/guide/compiler#how-directives-are-compiled

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

2 Comments

He's actually already done this, only difference is he appends before compiling rather than after.
Right, that what I answered so you need to append it to the DOM by yourself.
0

Your example and description is still mildly vague. Are you intending to include the template as a child inside your directive? Transclusion might be what you're after.

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.