AngularJS directive with isolate scope

42 views Asked by At

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

There are 2 answers

2
Mosh Feu On

$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

0
Mark Clark On

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.