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

人走茶凉 提交于 2019-12-25 00:39:24

问题


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:


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



来源:https://stackoverflow.com/questions/22356067/is-it-possible-to-transclude-while-keeping-the-scope-of-the-directive-in-angul

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