AngularJS在指令标记之间传递html内容

时间:2018-12-20 11:11:51

标签: javascript angularjs

我知道我可以做到:

<my-directive attr="myAttr"></my-directive>

,然后通过attr端访问my-directive

但是我想做这样的事情:

<my-directive attr="myAttr">
 <a href="">Some link that will apply with the my-directive directive too</a>
</my-directive>

这可能吗?

1 个答案:

答案 0 :(得分:1)

使用ng-transclude可以解决问题:

// html
<my-directive my-attr="Hello">
 <a href="#">My link</a>
</my-directive>

// my-directive.js 

app.directive("myDirective", function() {
 return {
  transclude: true,
  template: "<h1>{{myAttr}: <ng-transclude></ng-transclude></h1>", // <h1>Hello: <a href...>...</a></h1>
  scope: {
   myAttr: "@"
  },
  link: ($scope, element, attrs) => {

    console.log($scope.myAttr); // Hello

  }
 }
});

Read more here