指令内部的模板

Template inside of a directive

本文关键字:内部 指令      更新时间:2023-09-26

我有一个奇怪的情况,我需要把一个模板内的模板在我的指令。这样做的原因是AngularJS不会读取属性内部的ng-repeat代码。

在理想情况下,我的代码应该是这样的:

<div ng-repeat="phone in phones">
   <button popover="<div ng-repeat='friend in phone.friends'>{{friend.name}}</div>"></button>
</div>

不幸的是,由于popover属性周围的引号,这不起作用。这让我掉进了一个很深的兔子洞,我试图把一个模板放在一个模板里面,就像这个plunker:

http://plnkr.co/edit/ZA1uA1UOlU3cCH2mbE0X?p =

预览HTML:

<div my-popover></div>
Javascript:

angularApp.directive('myPopover', function( $compile) {
  var getTemplate = function()
  {
      var scope = {title: "other title"}; 
      var template = "<div> test template. title: {{title}}</div> ";
      return $compile(template)(scope); 
  }
    return {
        restrict: 'A',
        template: '<button class="btn btn-default" popover="{{content}}" popover-title="title">template</button>',
        link: function(scope) {
            scope.content = getTemplate();
        }
    };
})

不幸的是,这不起作用,因为AngularJs抱怨循环引用。请帮助!(这花了我一整天的时间)

我不确定我是否完全理解你想要实现的目标,但从来看你可能想要检查transclude选项的指令。

From the docs:

使用translude: true当你想创建一个包装指令任意内容。

如果你使用transclude,你可以将弹出窗口的内容存储在按钮中,并使用ng-transclude指令将这些内容"转发"到你想要的地方。

你的代码看起来像这样:

<button>
    <div ng-repeat='friend in phone.friends'>{{friend.name}}</div>
</button>

你可以在指令指南中看到一些实际的例子。