【问题标题】:AngularJS directive with isolate scope具有隔离范围的 AngularJS 指令
【发布时间】:2019-10-21 00:12:53
【问题描述】:

我有一个可能看起来像这样的指令:

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

当我编译以隔离范围时,它不起作用。没有显示内容。如果我编译到父范围,它似乎会起作用。我可以使用隔离范围吗?

谢谢

【问题讨论】:

标签: angularjs angularjs-directive angularjs-compile


【解决方案1】:

$compile 返回一个函数,当您调用它时会返回一个 元素,因此您需要自己将其附加到 DOM:

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

【讨论】:

  • 他实际上已经这样做了,唯一的区别是他在编译之前而不是之后追加。
  • 对,我回答的就是so you need to append it to the DOM by yourself
【解决方案2】:

您的示例和描述仍然有些模糊。您是否打算将模板作为子模板包含在您的指令中? Transclusion 可能就是你想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    相关资源
    最近更新 更多