简体   繁体   中英

Is it possible to 'transclude' while keeping the scope of the directive in Angular?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM