Is it possible to 'transclude' while keepi

2019-08-28 02:03发布

Is possible to do the following in 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>

My directive is simple but it's not working:

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

I also tried to use the transclude function to change the scope and it works. The only problem is that I loose the template.

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

Is it possible to do this while keeping the template in place and clone to be appended into the element with ng-transclude attribute?

Here is a Plnkr link you could use to test your solution: http://plnkr.co/edit/IWd7bnhzpLmlBpoaoJct?p=preview

1条回答
冷血范
2楼-- · 2019-08-28 02:39

That happened to you because you were too aggressive with the element.

You can do different things instead of replaceWith that will... replace the current element.

You can append it to the end, prepend it... pick one template element and insert it inside... Any DOM manipulation. For example:

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

Here I decided to put it after the element, so you could expect:

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

Notice I did not included ng-transclude on the template. It is not needed because you're doing that by hand.

So TL;DR;: Play with the element, don't just replace it, you can insert the transcluded html where you want it, just pick the right element, and call the right method on it.

For the sake of completeness here is another example: http://plnkr.co/edit/o2gkfxEUbxyD7QAOELT8?p=preview

查看更多
登录 后发表回答