簡體   English   中英

在AngularJS中的custom指令中包含第一個子html

[英]Include first child html in custom directive in AngularJS

我有一個angularjs指令,我加載了一個模板:

<div class="step" id="stepId" >
</div>

這是指令聲明:

angular.module('PortfolioApp')
  .directive('slideStep', function () {
return {
    templateUrl: appUrl + '/templates/slideStep.html',
    restrict: 'E',
      link: function postLink(scope, element, attrs) {
        //element.text('this is the slideStep directive');
          console.log("element text" +element.text());
      },
    replace:true
};
});

我想要實現的是,當我使用指令時包含的html包含在替換的html中。 例如:

<slide-step>
    <img src="images/HAC0.jpg"/>
</slide-step>

<div class="step" id="stepId" >
   <img src="images/HAC0.jpg"/>
</div>

有沒有辦法執行此任務允許將元素的HTML的第一個子項簡單綁定到自定義元素?

您需要使用transclusion:

https://docs.angularjs.org/api/ng/directive/ngTransclude

angular.module('PortfolioApp')
  .directive('slideStep', function () {
return {
    templateUrl: appUrl + '/templates/slideStep.html',
    restrict: 'E',
      link: function postLink(scope, element, attrs) {
        //element.text('this is the slideStep directive');
          console.log("element text" +element.text());
      },
    transclude:true,
};
});

並在您的指令模板中:

<div class="step" id="stepId" ng-transclude>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM