【问题标题】:Is it possible to 'transclude' while keeping the scope of the directive in Angular?是否可以在保持 Angular 指令范围的同时“嵌入”?
【发布时间】:2014-04-16 20:32:30
【问题描述】:

是否可以在 Angular 中执行以下操作?

<div ng-controller="MainCtrl" ng-init="name='World'">
    <test name="Matei">Hello {{name}}!</test> // I expect "Hello Matei"
    <test name="David">Hello {{name}}!</test> // I expect "Hello David"
</div>

我的指令很简单,但它不起作用:

app.directive('test', function() {
  return {
    restrict: 'E',
    scope: {
      name: '@'
    },
    replace: true,
    transclude: true,
    template: '<div class="test" ng-transclude></div>'
  };
});

我还尝试使用 transclude 函数来更改范围并且它有效。唯一的问题是我丢失了模板。

app.directive('test', function() {
  return {
    restrict: 'E',
    scope: {
      name: '@'
    },
    transclude: true,
    template: '<div class="test" ng-transclude></div>',
    link: function(scope, element, attrs, ctrl, transclude) {
      transclude(scope, function(clone) {
        element.replaceWith(clone);
      });
    }
  };
});

是否可以在保留模板并克隆以附加到具有ng-transclude 属性的元素的同时执行此操作?

这是一个 Plnkr 链接,您可以使用它来测试您的解决方案:http://plnkr.co/edit/IWd7bnhzpLmlBpoaoJct?p=preview

【问题讨论】:

  • Transclusion 改变了范围嵌套的方式,允许您包含绑定到外部范围的任意内容,这样您不必为它们提供模型。我会回到您的用例,并确切地确定您要在这里实现的目标。

标签: javascript angularjs angularjs-directive angularjs-scope


【解决方案1】:

这发生在你身上,因为你对元素过于激进。

您可以做不同的事情,而不是 replaceWith,这将...替换当前元素。

您可以将它附加到末尾,添加它...选择一个模板元素并将其插入...任何 DOM 操作。例如:

app.directive('test', function() {
  return {
    restrict: 'E',
    scope: {
      name: '@'
    },
    transclude: true,
    template: '<div class="test">This is test</div>',
    link: function(scope, element, attrs, ctrl, transclude) {
      transclude(scope, function(clone) {
        element.append(clone);
      });
    }
  };
});

这里我决定把它放在元素之后,所以你可以期待:

This is test
Hello Matei!
This is test
Hello David!

请注意,我没有在模板中包含 ng-transclude。不需要,因为您是手动操作的。

所以TL;DR;:玩元素,不要只是替换它,你可以在你想要的地方插入转置的html,只需选择正确的元素,并调用正确的方法就可以了。

为了完整起见,这里再举一个例子:http://plnkr.co/edit/o2gkfxEUbxyD7QAOELT8?p=preview

【讨论】:

    猜你喜欢
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 2013-02-06
    相关资源
    最近更新 更多