Dynamically adding an attribute Directive to a transclude Directive in AngularJS

非 Y 不嫁゛ 提交于 2019-12-11 08:31:44

问题


I'm attempting to dynamically add an attribute Directive to a transclude directive.

For example, the template would start off as follows:

<div class="container">
  <div ng-transclude></div>
</div>

After an event takes place (eg. a click), it would then have an attribute Directive added, such as:

<div class="container" some-directive>
  <div ng-transclude></div>
</div>

I'm using the following JavaScript to do this:

div = angular.element("#demoParentDirective .container").clone();
div.attr('some-directive','');
div = $compile(div)($scope);
angular.element("#demoParentDirective .container").replaceWith(div);

However, this results in:

Error: [ngTransclude:orphan] Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found. Element: <div ng-transclude="">

I've created a stripped down demo of what I'm trying to do in Plunker to show how I'm doing it:

http://plnkr.co/edit/xIKwJqKFbvs6DVnJrDUh?p=preview

Any help would be appreciated. Thanks.

Update:

As requested, I've created a follow-up question asking if there is a better way to achieve what it is I'm trying to achieve:

Creating a 'tab-away' attribute Directive with AngularJS


回答1:


Adding transclude to your child directive fixes the issue in your Plunk

angular.module('demo')
.directive('demoChildDirective', function() {
    return {
      restrict: "A",
      priority: 500,
      transclude: true,
      link: function(scope, element, attributes) {
        console.log("Child Directive Applied.");
      }
    }
  });


来源:https://stackoverflow.com/questions/30018941/dynamically-adding-an-attribute-directive-to-a-transclude-directive-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!